<template>
  <el-dialog v-if="isShow"
             :model-value="isShow"
             title="地理信息"
             :width="1200"
             :close-on-click-modal="false"
             :before-close="handleClose"

  >
    <div id="mapBox" >
      <div id="mapOperation" v-if="!isView">
        <el-tooltip class="box-item" effect="dark" content="清空标记" placement="right-start">
          <el-button @click="clearMapDraw"><el-icon><ElIconDelete /></el-icon></el-button>
        </el-tooltip>
      </div>
      <div id="mapContainer" ref="map">
      </div>
    </div>

    <template #footer v-if="!isView">
      <el-button type="primary" @click="sure">确认</el-button>
    </template>
  </el-dialog>
</template>

<script>
import 'ol/ol.css'
import { Map, View, Feature } from 'ol'
import * as Style from 'ol/style.js'
import * as Source from 'ol/source.js'
import * as Layer from 'ol/layer.js'
import TileLayer from 'ol/layer/Tile'
import OSM from 'ol/source/OSM'
import {GeoJSON} from "ol/format";
import {Draw} from "ol/interaction";
import {XYZ} from "ol/source";

export default {
  data() {
    return {
      map: null,
      type: '',
      geometry: {},
      category: {
        1: 'Point',
        2: 'LineString',
        3: 'Polygon',
        7: 'MultiPoint',
        8: 'MultiLineString',
        9: 'MultiPolygon'
      },
      drawStyle: new Style.Style({
        // 将点设置成圆形样式
        image: new Style.Circle({
          // 点的颜色
          fill: new Style.Fill({
            color: '#F00'
          }),
          // 圆形半径
          radius: 5
        }),
        // 线样式
        stroke: new Style.Stroke({
          color: '#F00',
          lineCap: 'round',       // 设置线的两端为圆头
          width: 3
        }),
        // 填充样式
        fill: new Style.Fill({
          color: 'rgba(248,152,152,0.5)'
        })
      })
    }
  },
  props: {
    isShow: Boolean,
    menuId: Number,
    geometryStr: String,
    isView: Boolean,
    callback: Function,
    close: Function
  },
  created() {
    let app = this;
    if (app.isView) {
      if (app.geometryStr && app.geometryStr!=='') {
      } else {
        app.$message({message: '数据为空，不支持查看', type: 'warning'});
        app.handleClose()
      }
    }
    this.$nextTick(()=>{
      setTimeout(app.initMap(), 100)
    })
    if (app.geometryStr) {
      app.geometry = JSON.parse(app.geometryStr)
    }
    if (app.menuId) {
      app.type = app.category[app.menuId]
    }
  },
  methods: {
    initMap() {
      let app = this;
      // 天地图底图
      let tileLayer = new TileLayer({
        title: '天地图',
        source: new XYZ({
          url: 'http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk='+systemConfig.tdt_tk,
        })
      })
      // 标注图层
      let tileMark = new TileLayer({
        title: '标注图层',
        source: new XYZ({
          url: 'http://t4.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk='+systemConfig.tdt_tk,
        })
      })
      app.map = new Map({
        target: app.$refs.map,
        logo: false,
        layers: [
          // new TileLayer({
          //   source: new OSM()
          // })
          tileLayer, tileMark
        ],
        view: new View({
          projection: 'EPSG:4326', // 使用这个坐标系
          center: [120.91634045937181, 27.943677724068422], // 中心点
          zoom: 14
        })
      })
      app.markerLayer = new Layer.Vector({
        source: new Source.Vector()
      });
      app.map.addLayer(app.markerLayer)
      if (!app.isView && app.type && app.type!=='') {
        app.draw(app.type);
      }
      if (app.geometry && app.geometry.type) {
        let feature = new GeoJSON().readFeature(app.geometry);
        feature.setStyle(app.drawStyle)
        app.markerLayer.getSource().addFeature(feature)
        app.map.getView().fit(feature.getGeometry().getExtent(), {size: app.map.getSize(),maxZoom: 14})
      }
    },
    clearMapDraw() {
      let source = this.markerLayer.getSource();
      source.getFeatures().forEach(i=>{
        source.removeFeature(i)
      })
    },
    draw(type) {
      let app = this;
      this.draw = new Draw({
        source: app.markerLayer.getSource(),
        type: type,
        style: app.drawStyle
      })
      app.map.addInteraction(app.draw)
      app.draw.on('drawend', e=>{
        if (app.menuId<7) {
          app.clearMapDraw();
        }
        e.feature.setStyle(app.drawStyle);
      })
    },
    getGeoJson() {
      let features = this.markerLayer.getSource().getFeatures();
      if (features.length>1) {
        let geoTool = new GeoJSON();
        let geometry = geoTool.writeFeatureObject(features[0]).geometry;
        for (let i = 1; i < features.length; i++) {
          geometry.coordinates.push(geoTool.writeFeatureObject(features[i]).geometry.coordinates[0])
        }
        return geometry;
      } else if (features.length===1) {
        let geometry = new GeoJSON().writeFeatureObject(features[0]).geometry;
        if (geometry.type.indexOf('Multi')===0) {
          geometry.type = geometry.type.substring(5);
          geometry.coordinates = geometry.coordinates[0];
        }
        return geometry;
      } else {
        return '';
      }
    },
    sure() {
      this.callback(this.getGeoJson());
      this.handleClose();
    },
    handleClose() {
      this.close(false)
    }
  }
}
</script>

<style scoped>
#mapBox {
  width: 100%;
  height: 100%;
  position: relative;
}
#mapContainer {
  width: 100%;
  height: 450px;
}
#mapOperation {
  position: absolute;
  right: 1%;
  top: 5%;
  z-index: 10;
}
</style>

<style>
.el-dialog__body {
  padding-top: 10px;
}
.ol-attribution {
  display: none !important;
}
</style>