<template>
  <el-dialog :class="'updateCenterDialog'" :visible.sync="isShow" width="75%" :close-on-click-modal="false"
    :before-close="dialogBeforeClose" append-to-body>
    <div id="map_geometry" class="map"></div>
    <span slot="title" class="dialog-title">
      <div class="title">
        <span>{{ title }}</span>
      </div>
    </span>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogBeforeClose"> 取 消 </el-button>
      <el-button type="primary" @click="sure">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import marker from "../../assets/img/marker-icon.png";

import Map from "ol/Map";
import View from "ol/View";
import Tile from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import { defaults } from "ol/control";
import { transform } from "ol/proj";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import { Icon, Style } from "ol/style";
import { Select, Modify, Draw } from "ol/interaction";
import DoubleClickZoom from "ol/interaction/DoubleClickZoom";

export default {
  props: {
    isShow: {
      type: Boolean,
      default: function () {
        return false;
      },
    },
    title: {
      type: String,
    },
    // geometry: {
    //   type: Object,
    // },
    // drawType: {
    //   type: Number,
    //   default: 0 // 0 点 1 线 2 面
    // },
    modelParams: {
      type: Object,
    },
    centerPoint: {
      type: Array,
      default: [114.5078337361353, 38.047503089608085],
    },
    beforeClose: {
      type: Function,
    },
    updateData: {
      type: Function,
    },
  },
  data() {
    return {
      zoom: 12,
      source: null,
      layer: null,
      centerPointMap: null,
      renderCenter: null,
    };
  },
  methods: {
    initMap() {
      let that = this;
      return new Promise(function (resolve, reject) {
        let layer = new Tile({
          source: new XYZ({ url: systemConfig.raster }),
          zIndex: 0,
        });
        let layer_annotation = new Tile({
          source: new XYZ({ url: systemConfig.raster_annotation }),
          zIndex: 1,
        });
        let national_boundary = new Tile({
          source: new XYZ({ url: systemConfig.national_boundary }),
          zIndex: 1,
        });
        that.centerPointMap = new Map({
          target: "map_geometry", //地图标签id
          logo: false,
          layers: [layer_annotation, layer, national_boundary],
          controls: defaults({
            attribution: false,
            zoom: false,
            rotate: false,
          }),
        });
        resolve();
      });
    },
    create() {
      //初始化矢量数据源
      this.source = new VectorSource({});

      //创建一个矢量图层
      this.vector = new VectorLayer({
        //数据源
        source: this.source,
        //样式
        style: new Style({
          image: new Icon({
            anchor: [0.5, 1],
            anchorOrigin: "top-left",
            crossOrigin: "anonymous",
            src: marker,
          }),
        }),
        zIndex: 2,
      });
    },
    addCenter() {
      let that = this;
      let view;
      view = new View({
        center: transform(
          [
            systemConfig.mapDefault.center.lng,
            systemConfig.mapDefault.center.lat,
          ],
          "EPSG:4326",
          "EPSG:3857"
        ),
        zoom: 11, // systemConfig.mapDefault.zoom,
        maxZoom: 18,
        constrainResolution: true, // 以整数级别缩放地图
      });

      if (that.renderCenter.length > 0) {
        let center_point = transform(
          that.renderCenter,
          "EPSG:4326",
          "EPSG:3857"
        );
        view = new View({
          center: center_point,
          zoom: that.zoom,
          maxZoom: 18,
          constrainResolution: true, // 以整数级别缩放地图
        });
        let poi = new Feature({
          geometry: new Point(center_point),
        });
        that.source.addFeature(poi);

        //创建一个交互选择对象
        that.select = new Select({
          //水平包裹
          wrapX: false,
        });

        //创建一个交互修改对象
        that.modify = new Modify({
          source: that.source,
        });

        // 创建 draw
        that.draw = new Draw({
          source: that.source,
          type: "Point",
        });
        that.draw.on("drawstart", function (evt) {
          that.centerPointMap.removeInteraction(that.doubleClickZoom);
        });

        that.draw.on("drawend", function (event) {
          that.clearSource();
          that.source.addFeature(
            new Feature({
              geometry: event.feature.values_.geometry,
            })
          );
          setTimeout(function () {
            that.centerPointMap.addInteraction(that.doubleClickZoom);
          }, 100);
        });

        this.centerPointMap.addInteraction(that.select);
        this.centerPointMap.addInteraction(that.modify);
        this.centerPointMap.addInteraction(that.draw);
      }
      this.centerPointMap.setView(view);
    },

    dialogBeforeClose() {
      this.beforeClose();
    },

    clearSource() {
      let that = this;
      if (this.source)
        this.source.getFeatures().forEach((element) => {
          that.source.removeFeature(element);
        });
    },
    sure() {
      this.updateData(
        transform(
          this.source.getFeatures()[0].getGeometry().getCoordinates(),
          "EPSG:3857",
          "EPSG:4326"
        )
      );
      this.dialogBeforeClose();
    },
  },
  watch: {
    isShow: {
      handler: function (newVal, oldVal) {
        let that = this;
        if (newVal) {
          if (this.centerPoint[0] != "" && this.centerPoint[1] != "") {
            this.renderCenter = this.centerPoint;
          } else {
            this.renderCenter = [114.5078337361353, 38.047503089608085];
          }
          this.$nextTick(function () {
            that.initMap().then(() => {
              that.doubleClickZoom = that.centerPointMap
                .getInteractions()
                .getArray()
                .find((interaction) => {
                  return interaction instanceof DoubleClickZoom;
                });
              that.create();
              this.centerPointMap.addLayer(that.vector);
              that.addCenter();
            });
          });
        } else {
          if (this.centerPointMap) {
            this.centerPointMap.removeInteraction(that.select);
            this.centerPointMap.removeInteraction(that.modify);
            this.centerPointMap.removeInteraction(that.draw);
            that.clearSource();
          }
          // $(".updateCenterDialog").remove();
        }
      },
      immediate: true,
    },
  },
};
</script>

<style lang="less" scoped>
.updateCenterDialog {
  /deep/ .el-dialog__header {
    border-bottom: 1px solid #e8e8e8;
    padding: 15px;
  }

  .title {
    height: 30px;
    line-height: 30px;
    font-size: 20px;
    font-weight: bold;
  }

  /deep/ .el-dialog__body {
    padding: 0 0;
  }

  /deep/ .el-dialog__footer {
    border-top: 1px solid #eeeeee;
    padding: 10px 20px;
  }

  .el-form-item {
    /deep/ .el-form-item__label {
      width: 100px !important;
    }

    /deep/ .el-form-item__content {
      margin-left: 100px !important;
    }
  }

  #map_geometry {
    height: 500px;
  }
}
</style>