<template>
  <div class="map-container">
    <nav>
      <map-selector :default-val="formData.mapId" @setMapInfo="handleSelectMap" />
      <!-- <div class="page-title">
        现场分布图
      </div> -->
      <el-button size="mini" type="primary" style="margin-left:15px;" @click="submit">保存</el-button>
    </nav>
    <div class="layout-map">
      <div class="left-side">
        <div class="title">作业项目</div>
        <div v-for="(item,index) in markerItems" :key="index" :class="checkItemIndex===index?'item active':'item'" @click="checkItem(item,index)">
          <img :src="item.icon" alt="" class="icon">
          <div class="name">{{ item.name }}</div>
        </div>
      </div>
      <div id="vmap" />
      <div class="rightSide">
        <div v-if="type==1" class="remark">
          <div class="title">使用说明</div>
          <ul>
            <li>1.点击作业项目下面的图标</li>
            <li>2.点击地图绘制点</li>
            <li>3.编辑信息保存点位</li>
          </ul>
        </div>
        <div v-if="type==2||type=='drage'" class="saveForm">
          <div class="title">新增标记点</div>
          <div class="item">
            <div class="lable">矿带：</div>
            <div class="content">
              <el-select v-model="saveForm.goafOrebelt" class="safe-area-item" filterable clearable placeholder="矿带">
                <el-option :value="0" label="请选择矿带" disabled />
                <el-option v-for="(item,index) in goaf" :key="index" :value="item.goafOrebelt" :label="item.goafOrebelt" />
              </el-select>
            </div>
          </div>
          <div class="item">
            <div class="lable">矿体：</div>
            <div class="content">
              <el-select v-model="saveForm.goafOrebody" class="safe-area-item" filterable clearable placeholder="矿体">
                <el-option :value="0" label="请选择矿体" disabled />
                <el-option v-for="(item,index) in goaf" :key="index" :value="item.goafOrebody" :label="item.goafOrebody" />
              </el-select>
            </div>
          </div>
          <div class="item">
            <div class="lable">中段：</div>
            <div class="content">
              <el-select v-model="saveForm.goafOreheight" class="safe-area-item" filterable clearable placeholder="中段">
                <el-option :value="0" label="请选择中段" disabled />
                <el-option v-for="(item,index) in goaf" :key="index" :value="item.goafOreheight" :label="item.goafOreheight" />
              </el-select>
            </div>
          </div>
          <div class="item">
            <div class="lable">采空区：</div>
            <div class="content">
              <el-select v-model="saveForm.goafName" class="safe-area-item" filterable clearable placeholder="采空区名称">
                <el-option :value="0" label="请选择采空区" disabled />
                <el-option v-for="(item,index) in goaf" :key="index" :value="item.goafName" :label="item.goafName" />
              </el-select>
            </div>
          </div>
          <div class="bt-wrap">
            <div class="bt save" @click="save">保存</div>
            <div class="bt margin" @click="cancel">撤销</div>
          </div>
        </div>
        <div v-if="type==3" class="deleteForm">
          <div class="title">删除标记点</div>
          <div class="item">
            <div class="lable">矿带：</div>
            <div class="content"> {{ deleteForm.goafOrebelt }}</div>
          </div>
          <div class="item">
            <div class="lable">矿体：</div>
            <div class="content"> {{ deleteForm.goafOrebody }}</div>
          </div>
          <div class="item">
            <div class="lable">中段：</div>
            <div class="content"> {{ deleteForm.goafOreheight }}</div>
          </div>
          <div class="item">
            <div class="lable">采空区：</div>
            <div class="content"> {{ deleteForm.goafName }}</div>
          </div>
          <div class="bt-wrap">
            <div class="bt" @click="save">保存</div>
            <div class="bt delete margin" @click="delMarker">删除</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as L from 'leaflet'
import '@geoman-io/leaflet-geoman-free'
import { mapGetters } from 'vuex'
import MapSelector from '@/components/MapSelector'
import { getMapLayerByList } from '@/api/system/mapLayerApi'
import { getGoafBaseInfo } from '@/api/goaf/info'
import { getMapLayerById, createMapLayer, delMapLayer, updateMapLayer } from '@/api/goaf/layer'
const markerIcon = L.icon({
  iconUrl: require('@/assets/images/icon/4.png'),
  shadowUrl: require('@/assets/images/icon/4hover.png'),
  iconSize: [60, 70],
  shadowSize: [60, 70],
  iconAnchor: [16, 52],
  popupAnchor: [1, -38]
})
L.Marker.prototype.options.icon = markerIcon
export default {
  name: 'GoafVisualEditor',
  components: {
    MapSelector
  },
  data() {
    return {
      viewData: {},
      formData: {
        mapId: undefined,
        layerId: undefined,
        layerVector: ''
      },
      type: 1,
      checkItemIndex: -1,
      state: 0,
      markerId: undefined,
      veditId: undefined,
      dragstartMarker: undefined,
      markerItems: [
        { icon: require('@/assets/images/icon/4.png'), name: '' }
      ],
      map: undefined,
      geoLayer: undefined,
      conditions: {
        layerId: undefined
      },
      saveForm: {
        'goaflayerId': '',
        'ocId': '',
        'goafId': '',
        'goafOrebelt': 0,
        'goafOrebody': 0,
        'goafOreheight': 0,
        'goafName': '',
        'mapId': '',
        'layerId': '',
        'layerCatId': '',
        'layerTitle': '',
        'layerMarker': '',
        'layerVector': '',
        'layerVectorType': ''
      },
      deleteForm: {
        'icon': '',
        'name': '',
        'goaflayerId': '',
        'ocId': '',
        'goafId': '',
        'goafOrebelt': 0,
        'goafOrebody': 0,
        'goafOreheight': 0,
        'goafName': '',
        'mapId': '',
        'layerId': '',
        'layerCatId': '1',
        'layerTitle': '',
        'layerMarker': '',
        'layerVector': '',
        'layerVectorType': ''
      },
      layer: null,
      layers: [],
      layerGroup: [],
      imageOverlay: undefined,
      goaf: []
    }
  },
  computed: {
    ...mapGetters([
      'userData'
    ])
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.initMap()
      getGoafBaseInfo().then((res) => {
        this.goaf = res.data
      })
    },

    // 加载数据
    load(layerId) {
      this.conditions.layerId = layerId
      this.getData()
    },
    // 初始化
    getData() {
      getMapLayerById(this.conditions.layerId).then((resp) => {
        const { code, data, msg } = resp
        if (code === 0) {
          this.viewData = data
          this.setRasterLayer()
        } else {
          this.$message.error(msg)
        }
      })
    },

    // 初始化地图
    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: false,
        zoomControl: true // zoomControl（缩放控制）：确定缩放控制是否默认加载在地图上。
      })
      this.geoLayer = L.geoJson(null, { pmIgnore: false })
      this.geoLayer.addTo(this.map)
      this.mapListener()
      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) {
      this.viewData.mapRasterLayer = obj.mapRasterLayer
      this.viewData.mapId = obj.mapId
      this.formData.mapId = obj.mapId
      this.setRasterLayer()
    },
    createMapLayer() {
      createMapLayer().then(() => {

      })
    },
    formSuccess() {
      this.$emit('formSuccess')
    },
    mapListener() {
      this.map.on('pm:drawstart', (e) => { // 绘制开始时事件
        if (e.shape === 'Marker') {
          const iconUrl = this.saveForm.icon
          const layer = e.workingLayer
          var icon = L.icon({
            iconUrl,
            shadowUrl: iconUrl,
            shadowSize: [60, 70],
            iconSize: [60, 70]
          })
          layer.setIcon(icon)
        }
      })
      this.map.on('pm:create', (e) => {
        const self = this
        if (e.shape === 'Marker') {
          const iconUrl = this.saveForm.icon
          const name = this.saveForm.name
          const typeId = this.checkItemIndex + 1
          const layer = e.layer
          var icon = L.icon({
            iconUrl,
            shadowUrl: iconUrl,
            name,
            typeId,
            shadowSize: [60, 70],
            iconSize: [60, 70]
          })
          layer.setIcon(icon)
          self.layer = layer
          layer.addTo(this.layerGroup)
          layer.on('click', (ev) => {
            if (self.type === 2) {
              layer.dragging.enable()
            }
          })
          layer.on('dragend', function(ev) {
            self.layer = ev.target
          })
        }
        this.map.pm.disableDraw(e.shape)
      })
    },
    // 获取地图图层数据
    getMapLayers() {
      const obj = {}
      obj.mapId = this.mapId
      getMapLayerByList(obj).then((resp) => {
        const { code, data, msg } = resp
        if (code === 0) {
          this.mapLayerList = data
          this.initMapLayers()
        } else {
          this.$message.error(msg)
        }
      })
    },

    // 初始化地图图层
    initMapLayers() {
      const self = this
      const layerList = this.mapLayerList
      const feature = []
      this.layerGroup = L.layerGroup().addTo(this.map)

      if (layerList != null && layerList.length > 0) {
        layerList.forEach((item) => {
          item.layerMarker && feature.push(JSON.parse(item.layerMarker))
          item.layerVector && feature.push(JSON.parse(item.layerVector))
        })
        L.geoJSON(feature, {
          // pointToLayer: function(_feature, latlng) {
          //   // var smallIcon = L.Icon({
          //   //   options: {
          //   //     iconSize: [27, 27],
          //   //     iconAnchor: [13, 27],
          //   //     popupAnchor: [1, -24],
          //   //     iconUrl: 'icone/chapel-2.png'
          //   //   }
          //   // })
          //   // return L.marker(latlng, { icon: smallIcon })
          // },
          onEachFeature: (_feature, layer) => {
            this.layerGroup.addLayer(layer)
            layer.on('click', (ev) => {
              if (self.type === 2 || self.type === 'drage') {
                self.$message.success('请先确认当前标记点操作！')
                return
              }
              self.type = 3
              self.layer = ev.target
              layer.dragging.enable()
            })
            layer.on('dragstart', function(ev) {
              if (self.dragstartMarker === undefined) {
                self.dragstartMarker = { layer, latlng: ev.target._latlng }
              }
            })
            layer.on('dragend', function(ev) {
              self.type = 'drage'
              self.layer = ev.target
            })
          }
        }).addTo(this.layerGroup)
      }
    },
    clearLayers() {
      this.layerGroup.clearLayers()
    },
    submit() {
      // 图层操作完，一次导出geoJSON
      const layers = this.map._layers
      console.log({
        layers,
        geoLayer: this.geoLayer,
        geoJson: this.createGeoJson()
      })
    },
    checkItem(item, index) {
      if (this.state === 1) {
        this.$message('请保存后再操作！')
        return
      }
      this.checkItemIndex = index
      this.type = 2
      this.state = 1
      this.saveForm.icon = item.icon
      this.saveForm.name = item.name
      this.map.pm.enableDraw('Marker', { snappable: false, tooltips: false })// tooltips: { 'placeMarker': '点击放置标记' },
    },
    save() {
      if (this.type === 3) {
        // 删除表单里面的保存
        this.type = 1
      } else if (this.type === 'drage') {
        updateMapLayer({
          // 'goaflayerId': '',
          'ocId': this.userData.ocId,
          // 'goafId': '',
          'goafOrebelt': this.saveForm.goafOrebelt,
          'goafOrebody': this.saveForm.goafOrebody,
          'goafOreheight': this.saveForm.goafOreheight,
          'goafName': this.saveForm.goafName,
          'mapId': this.formData.mapId,
          'layerId': '',
          'layerCatId': '',
          'layerTitle': '',
          'layerMarker': this.layer?.toGeoJSON(),
          'layerVector': '',
          'layerVectorType': ''
        }).then(() => {
          this.type = 1
          this.checkItemIndex = -1
          this.state = 2
          this.resetForm()
          this.$message.success('修改成功！')
          this.dragstartMarker = undefined
          // this.getLayers()
        })
      } else {
        // 新增
        createMapLayer({
          // 'goaflayerId': '',
          'ocId': this.userData.ocId,
          // 'goafId': '',
          'goafOrebelt': this.saveForm.goafOrebelt,
          'goafOrebody': this.saveForm.goafOrebody,
          'goafOreheight': this.saveForm.goafOreheight,
          'goafName': this.saveForm.goafName,
          'mapId': this.formData.mapId,
          'layerId': '',
          'layerCatId': '',
          'layerTitle': '',
          'layerMarker': this.layer?.toGeoJSON(),
          'layerVector': '',
          'layerVectorType': ''
        }).then(() => {
          this.type = 1
          this.checkItemIndex = -1
          this.state = 2
          this.resetForm()
          this.$message.success('新增成功！')
          // this.getLayers()
        })
      }
    },
    cancel() {
      this.state = 2
      this.checkItemIndex = -1
      this.resetForm()
      if (this.type === 'drage') {
        this.type = 1
        this.dragstartMarker.layer.setLatLng(this.dragstartMarker.latlng)
        this.dragstartMarker.layer.dragging.disable()
        this.dragstartMarker = undefined
        return
      }
      if (this.layer && this.layer._leaflet_id && this.map._layers[this.layer._leaflet_id]) {
        this.map.removeLayer(this.map._layers[this.layer._leaflet_id])
        this.layer = undefined
        this.type = 1
      }
    },
    delMarker() {
      delMapLayer(this.veditId).then(() => {
        this.type = 1
        this.state = 2
        this.checkItemIndex = -1
        this.resetForm()
        this.$message.success('删除成功！')
        // this.getLayers()
      })
    },
    resetForm() {
      const data = {
        'icon': '',
        'name': '',
        'goaflayerId': '',
        'ocId': '',
        'goafId': '',
        'goafName': '',
        'mapId': '',
        'layerId': '',
        'layerCatId': '',
        'layerTitle': '',
        'layerMarker': '',
        'layerVector': '',
        'layerVectorType': ''
      }
      this.saveForm = JSON.parse(JSON.stringify(data))
      this.deleteForm = JSON.parse(JSON.stringify(data))
    },
    drawLayer(params, map = this.map) {
      var layer = null
      const _latlng = params.geometry.coordinates.latlng
      const latlng = Array.isArray(_latlng) ? _latlng(item => [item.lat, item.lng]) : [_latlng.lat, _latlng.lng]
      switch (params.type) {
        case 'Marker' :
          layer = L.marker([latlng]).addTo(map)
          break
        case 'Line' :
          layer = L.polyline([latlng]).addTo(map)
          break
        case 'Circle' :
          layer = L.circle([latlng], {
            color: 'red',
            fillColor: '#f03',
            fillOpacity: 0.5,
            radius: params.properties.radius
          }).addTo(map)
          break
        case 'Rectangle' :
          layer = L.rectangle(latlng).addTo(map)
          break
        case 'Polygon' :
          layer = L.polygon(latlng).addTo(map)
          break
      }
      return layer
    },
    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
    }
  }
}
</script>
    <style lang="scss" scoped>
    .map-container{
        padding: 15px;
        nav{
            height: 60px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 16px;
            box-sizing: border-box;
            background-color: #193142;
            .page-title {
                font-size: 18px;
                font-weight: bold;
                color: #FFFFFF;
                font-weight: bold;
            }
        }
        .layout-map{
            display: flex;
            justify-content: space-between;
            height: calc(100vh - 160px);
            margin-top: 10px;
            .left-side{
                min-width: 266px;
                height: 100%;
                overflow-y: auto;
                background-color: #193142;
                box-sizing: border-box;
                .title{
                    height: 42px;
                    line-height: 42px;
                    background-color: #36556b;
                    font-size: 16px;
                    color: #666;
                    text-indent: 10px;
                    color: #fff;
                }
                .item{
                    display: flex;
                    align-items: center;
                    height: 48px;
                    padding-left: 10px;
                    cursor: default;
                    &.active{
                        background-color: rgba(45, 140, 240, 0.16);
                    }
                    .icon{
                        width: 30px;
                        display: block;
                    }
                    .name{
                        font-size: 14px;
                        padding-left: 12px;
                        color: #fff;
                    }
                }
            }
            #vmap {
                height: 100%;
                flex: 1;
                background: #8c939d;
                box-sizing: border-box;
            }
            .rightSide{
                width: 269px;
                height: 100%;
                overflow-y: auto;
                background-color: #193142;
                box-sizing: border-box;
                padding: 17px 16px;
                color: #fff;
                .title{
                    color: #fff;
                    font-size: 16px;
                    margin-bottom: 16px;
                }
                .remark{
                    ul,li{
                        list-style: none;
                        margin: 0;
                        padding: 0;
                    }
                    li{
                        color: rgba(255, 255, 255, 0.7);
                        line-height: 28px;
                        font-size: 14px;
                        margin-bottom: 8px;
                    }
                }
                .saveForm,.deleteForm{
                    .item{
                        height: 48px;
                        display: flex;
                        justify-content: flex-start;
                        align-items: center;
                        font-size: 14px;
                        border-bottom:2px solid rgba(45, 140, 240, 0.16);
                        .lable{
                        width: 80px;
                        font-size: 14px;
                        }
                        .content{
                        display: flex;
                        justify-content: flex-start;
                        align-items: center;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        .icon{
                            width: 17.5px;
                            display: block;
                            margin-right:8px;
                        }
                        }
                    }
                }
                .bt-wrap{
                    margin-top: 65px;
                    .bt{
                        width: 100px;
                        height: 36px;
                        color: #fff;
                        font-size: 14px;
                        line-height: 36px;
                        text-align: center;
                        background-color: rgba(24, 144, 255, 0.3);
                        display: inline-block;
                        cursor: pointer;
                        user-select: none;
                    -moz-user-select: none;
                    -webkit-user-select: none;
                    -ms-user-select: none;
                        &.save{
                        background-color: #1890ff;
                        }
                        &.delete{
                        background-color: #f97647;
                        }
                        &.margin{
                            margin-left: 12px;
                        }
                    }
                }

            }
        }

    }
    </style>

