<template>
  <div id="content">
    <div id="map" ref="map"></div>
    <div id="popup" class="ol-popup" style="background-color: #fff">
      <span>查看详情</span>
      <div id="popup-closer" class="popup-closer">
        <i class="el-icon-error"></i>
      </div>
      <div id="popup-content" class="popup-content"></div>
    </div>
  </div>
</template>

<script>
import "ol/ol.css";
import { Map, View } from "ol";
import { defaults as defaultControls } from "ol/control";
import Tile from "ol/layer/Tile";
import { fromLonLat } from "ol/proj";
import OSM from "ol/source/OSM";
import WMTS from "ol/source/WMTS";
import WMTSTileGrid from "ol/tilegrid/WMTS.js";
import VectorSource from "ol/source/Vector.js";
import Cluster from "ol/source/Cluster.js";
import { TileSuperMapRest } from "@supermap/iclient-ol/mapping/TileSuperMapRest";

import VectorLayer from "ol/layer/Vector.js";
import { Style, Fill, Stroke, Circle, Text } from "ol/style";

import { Draw, Select } from "ol/interaction";
import { SingleClick } from "ol/events/condition";

import Feature from "ol/Feature.js";
import LineString from "ol/geom/LineString.js";
import Point from "ol/geom/Point.js";
import { WMTSCapabilities, GML2 } from "ol/format";
import { getWidth, getTopLeft } from "ol/extent";
import GeoJSON from "ol/format/GeoJSON.js";
import Overlay from "ol/Overlay";

import guangdongJson from "./guangdong.json";

import { listInfo } from "@/api/build/projectInfo";

export default {
  props: {
    potMsg: { type: Array },
    lineMsg: { type: Array },
    allDrawMsg: { type: Array },
  },
  data() {
    return {
      map: null,
      // projection: "EPSG:4326",
      pointDrawFlag: "",
      lineDrawFlag: "",
      sketch: "", // 存储草图
      geometries: [], // 存储绘制的几何图形
      lastPointFeature: null,
      lastLineFeature: null,
      all_draw_feature: [],
      all_point_coords: [],
      all_line_coords: [],
      pointVectorSource: null,
      lineVectorSource: null,
      ClusterSource: null,
      pointVectorLayer: null,
      lineVectorLayer: null,
      zoom: 10,
      interaction: null,
      lonALat: {
        lon: null,
        lat: null,
      },
      viewCenter: [113.36502, 22.9787],

      // 重大项目字典
      zd_projectTypeOptions: [],
      // 面上项目字典
      ms_projectTypeOptions: [],
      // 建设性质字典
      constructionNatureOptions: [],
    };
  },
  created() {
    this.getDicts("major_project").then((response) => {
      this.zd_projectTypeOptions = response.data;
    });
    this.getDicts("general_project").then((response) => {
      this.ms_projectTypeOptions = response.data;
    });
    this.getDicts("CONSTRUCTION_NATURE").then((response) => {
      this.constructionNatureOptions = response.data;
    });
    if (this.potMsg.length > 0 || this.lineMsg.length > 0) {
      this.all_point_coords = [...this.potMsg];
      this.all_line_coords = [...this.lineMsg];
      this.all_draw_feature = [...this.allDrawMsg];
    }
  },
  mounted() {
    this.initMap();
    this.getProjectInfo();
    window.addEventListener("click", this.projectNameClick);
  },
  beforeDestroy() {
    window.removeEventListener("click", this.projectNameClick);
  },

  methods: {
    projectNameClick(e) {
      console.log(e);
      if (e.target.id == "projectName") {
        console.log(e.target.dataset.pid[0]);
        this.$router.push({
          path:
            "/building/projectInfo/projectProcess?baseDataId=" +
            e.target.dataset.pid[0],
        });
      }
      return;
    },
    /**
     * 初始化一个 openlayers 地图
     */
    initMap() {
      let that = this;
      const projection = "EPSG:4326";
      this.map = new Map({
        target: "map",
        view: new View({
          center: that.viewCenter,
          zoom: 10,
          // maxZoom: 12,
          minZoom: 5,
          projection: projection,
          multiWorld: true,
        }),
      });
      var matrixIds = new Array(18);
      var resolutions = [];
      for (var z = 0; z < 18; ++z) {
        var res = 360 / 512; //0.703125
        resolutions[z] = res / Math.pow(2, z - 1);
        matrixIds[z] = z;
      }

      // 加载第一层地图轮廓图层
      var osm = new Tile({
        source: new WMTS({
          url: "http://t0.tianditu.gov.cn/img_c/wmts?tk=42a5dfa93ea7a9cbf423c4c1bb9ec16d",
          service: "wmts",
          version: "1.0.0",
          matrixSet: "c",
          layer: "img",
          format: "Tile",
          projection: "EPSG:4326",
          tileGrid: new WMTSTileGrid({
            extent: [-180, -90, 180, 90],
            origin: [-180, 90],
            resolutions: resolutions,
            matrixIds: matrixIds,
          }),
          style: "default",
          // wrapX: false
        }),
      });
      this.map.addLayer(osm);

      // let point = new Point([115.36502, 22.7787]);
      // this.map.addLayer(point);

      // 加载其他数据图层
      // 所需展示的所有图层列表
      // 不同类型的地图服务主要区分于type
      const layerList = [
        // {
        //   index: 0,
        //   code: 'YZT1610609202768',
        //   name: '广东2020年7_17级矢量图',
        //   url: 'http://19.25.37.27:8081/gmap/proxyHandler?serviceCode={{serviceCode}}&url=https://ztn-data.gdgov.cn:8581/GatewayMsg/http/api/proxy/invoke',
        //   type: 'YZT-WMTS'
        // },
        // {
        //   index: 1,
        //   code: "YZT1597746916315",
        //   name: "广东7_17级界线电子地图",
        //   url: "http://19.25.37.27:8081/gmap/proxyHandler?serviceCode={{serviceCode}}&url=https://ztn-data.gdgov.cn:8581/GatewayMsg/http/api/proxy/invoke",
        //   type: "YZT-WMTS",
        // },
        {
          index: 2,
          code: "YZT1610609681389",
          name: "广东2020年7_17级矢量注记",
          url: "http://19.25.37.27:8081/gmap/proxyHandler?serviceCode={{serviceCode}}&url=https://ztn-data.gdgov.cn:8581/GatewayMsg/http/api/proxy/invoke",
          type: "YZT-WMTS",
        },
        {
          index: 3,
          code: "0",
          text: "",
          url: "http://19.25.37.25:8090/iserver/services/map-XingZhengQuHua/rest/maps/行政区划",
          type: "rest-map",
        },
        // {
        //   index: 4,
        //   code: "0",
        //   text: "",
        //   url: "http://19.25.35.204:31190/iserver/services/map-GuangDongShengDaoLu/rest/maps/广东省道路",
        //   type: "rest-map",
        // },
        {
          index: 5,
          code: "0",
          text: "",
          url: "http://19.25.35.204:31190/iserver/services/map-ShengJiXingZhengQuHuaMian/rest/maps/省级行政区划面",
          type: "rest-map",
        },
        // {
        //   index: 6,
        //   code: '0',
        //   text: '',
        //   url: 'http://19.25.35.204:31190/iserver/services/map-YiZhangTuShuiKu/rest/maps/水库',
        //   type: 'rest-map'
        // },
        // {
        //   index: 7,
        //   code: '0',
        //   text: '',
        //   url: 'http://19.25.35.204:31190/iserver/services/map-ShiJiXingZhengQuHuaMian/rest/maps/市级行政区划面',
        //   type: 'rest-map'
        // },
        // {
        //   index: 8,
        //   code: '0',
        //   text: '',
        //   url: 'http://19.25.35.204:31190/iserver/services/map-XianJiXingZhengQuHuaMian/rest/maps/县级行政区划面',
        //   type: 'rest-map'
        // },
        // {
        //   index: 9,
        //   code: '0',
        //   text: '',
        //   url: 'http://19.25.35.204:31190/iserver/services/map-ZhenJiXingZhengQuHuaMian/rest/maps/镇级行政区划面',
        //   type: 'rest-map'
        // },
        // {
        //   index: 10,
        //   code: '0',
        //   text: '',
        //   url: 'http://19.25.35.204:31190/iserver/services/map-CunJiXingZhengQuHuaMian/rest/maps/村级行政区划面',
        //   type: 'rest-map'
        // }
        {
          index: 11,
          code: "0",
          text: "",
          url: "http://19.25.35.204:31190/iserver/services/map-YiZhangTuShuiZha/rest/maps/水闸",
          type: "rest-map",
        },
        {
          index: 12,
          code: "0",
          text: "",
          url: "http://19.25.35.204:31190/iserver/services/map-YiZhangTuDiFang/rest/maps/堤防",
          type: "rest-map",
        },
      ];
      // 绘制图层列表
      for (let i = 0; i < layerList.length; i++) {
        loadIndex(layerList[i].type, i);
      }

      // 初始化绘制点、线图层
      // 创建一个矢量数据源
      this.pointVectorSource = new VectorSource({
        wrapX: false,
      });
      // 创建一个矢量图层并将数据源与之关联
      this.pointVectorLayer = new VectorLayer({
        source: this.pointVectorSource,
        style: new Style({
          fill: new Fill({
            color: "rgba(255, 255, 255, 0.2)", // 填充颜色
          }),
          stroke: new Stroke({
            // color: "#409eff", // 边框颜色
            width: 4, // 边框宽度
          }),
          image: new Circle({
            radius: 8, // 圆点半径
            fill: new Fill({
              color: "blue", // 圆点填充颜色
            }),
          }),
        }),
      });
      this.lineVectorLayer = new VectorLayer({
        source: this.lineVectorSource,
        style: new Style({
          fill: new Fill({
            color: "rgba(255, 255, 255, 0.2)", // 填充颜色
          }),
          stroke: new Stroke({
            // color: "#409eff", // 边框颜色
            width: 4, // 边框宽度
          }),
          image: new Circle({
            radius: 8, // 圆点半径
            fill: new Fill({
              color: "blue", // 圆点填充颜色
            }),
          }),
        }),
      });
      // this.map.addLayer(this.pointVectorLayer);
      this.map.addLayer(this.lineVectorLayer);

      // 监听事件
      // 监听点图层的change事件来获取点坐标

      // this.map.getViewport().addEventListener('click', () => {
      //    this.pointVectorSource.on('addfeature', (event) => {
      //     const coordinate = event.feature.getGeometry().getCoordinates();
      //     console.log(coordinate);
      //   });
      // });

      function loadIndex(type, index) {
        var path = "";
        if (type === "YZT-WMTS") {
          path = "?SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetCapabilities";
        } else if (type === "rest-map") {
        } else {
          path = "VERSION=1.0.0&REQUEST=GetFeature&SERVICE=WFS";
        }
        let xhr = new XMLHttpRequest();
        let sign = "";
        xhr.open(
          "GET",
          layerList[index].url.replace(
            /{{serviceCode}}/,
            layerList[index].code
          ) +
            sign +
            path
        );
        xhr.onload = function () {
          let data = xhr.response;
          if (type === "YZT-WMTS") {
            addYztWmtsLayer(data, index);
          } else if (type === "YZT-YSFW") {
            addYsfwLayer(data, index);
          } else {
            addRestMapLayer(layerList[index], index);
          }
        };
        xhr.send();
      }

      // 加载wmts服务
      function addYztWmtsLayer(res, index) {
        console.log(layerList[index]);
        console.log("加载次数");
        // console.log("输出WMTS服务数据", res);
        var format = new WMTSCapabilities();
        if (!res) {
          return;
        }
        var result = format.read(res);
        const item = result.Contents.Layer[0];
        const layerParam = {
          layerName: item.Abstract || item.Title,
          styleName: item.Style[0].Identifier,
          tilematrixset: item.TileMatrixSetLink[0].TileMatrixSet,
          format: item.Format[0],
        };
        var projectionExtent = [-180, -90, 180, 90];
        const size = getWidth(projectionExtent) / 256;
        const resolutionsYzt = [];
        const matrixIdsTzt = [];
        for (var z = 2; z < 19; ++z) {
          resolutionsYzt[z] = size / Math.pow(2, z);
          matrixIdsTzt.push(z - 2);
        }
        const source = new WMTS({
          url:
            layerList[index].url.replace(
              /{{serviceCode}}/,
              layerList[index].code
            ) +
            "?layer=" +
            layerParam.layerName,
          style: layerParam.styleName,
          matrixSet: layerParam.tilematrixset,
          format: layerParam.format,
          wrapX: true,
          tileGrid: new WMTSTileGrid({
            origin: getTopLeft(projectionExtent),
            resolutions: resolutionsYzt,
            matrixIds: matrixIdsTzt,
          }),
        });
        let lastIndex = index + 10 * (1 + index);
        var layer = new Tile({
          id: lastIndex,
          source: source,
        });
        console.log(source.urls);
        layer.setZIndex(lastIndex);
        that.map.addLayer(layer);
      }
      // -------------------------------------------------------------------------------------
      // 接入粤政图要素服务(wfs)
      function addYsfwLayer(res, index) {
        console.log("输出WFS服务数据", res);
        var result = res;
        var format = new GML2();
        var features = format.readFeatures(result);
        var style = null;
        if (features[0].getGeometry() instanceof ol.geom.Polygon) {
          style = new Style({
            stroke: new Stroke({
              color: "#868f98",
              width: 1,
            }),
            fill: new Fill({
              color: "#DEECFB",
            }),
          });
        } else if (features[0].getGeometry() instanceof ol.geom.Point) {
          features.forEach((each) => {
            var info = each.values_;
            var name = "";
            for (let key in info) {
              if (key.indexOf("名称") > -1) {
                name = info[key];
                break;
              }
            }
            style = new Style({
              image: new Circle({
                fill: new Fill({
                  color: "#ff0721",
                }),
                radius: 5,
              }),
              text: new Text({
                text: name,
                offsetY: 30,
                font: "12px Calibri,sans-serif",
                fill: new Fill({
                  color: "#fff",
                }),
                stroke: new Stroke({
                  color: "#f00",
                  width: 3,
                }),
              }),
            });
            each.setStyle(style);
          });
        } else if (features[0].getGeometry() instanceof ol.geom.LineString) {
          style = new Style({
            stroke: new Stroke({
              color: "#2899fb",
              width: 4,
            }),
          });
        }
        var source = new VectorSource({
          features: features,
        });
        var wfsObj = { source: source, style: style };

        var vectorLayer = new VectorLayer({
          id: layerList[index].code,
          source: wfsObj.source,
          style: wfsObj.style,
        });
        that.map.addLayer(vectorLayer);
      }

      // 接入rest-map服务
      function addRestMapLayer(params, index) {
        var restLayer = new Tile({
          source: new TileSuperMapRest({
            url: params.url,
            prjCoordSys: { epsgCode: 4326 },
            projection: "EPSG:4326",
          }),
        });
        let lastIndex = index + 10 * (1 + index);
        restLayer.setZIndex(lastIndex);
        that.map.addLayer(restLayer);
      }

      // 缩放
      this.map.on("moveend", function () {
        that.zoom = that.map.getView().getZoom();
        console.log("zomm", that.zoom);
      });
      // 鼠标移入元素样式
      this.map.on("pointermove", (e) => {
        let pixel = this.map.getEventPixel(e.originalEvent);
        let feature = this.map.forEachFeatureAtPixel(pixel, (feature) => {
          return feature;
        });

        if (feature != undefined) {
          this.map.getTargetElement().style.cursor = "pointer";
        } else {
          this.map.getTargetElement().style.cursor = "auto";
        }
      });

      // this.addGuangdongJson();
      this.ProjectCoordinatePoint();
      this.addPopup();
    },

    // 加载guangdong.json图层
    addGuangdongJson() {
      let that = this;
      let features = new GeoJSON().readFeatures(guangdongJson);
      let vectorSource = new VectorSource({
        features: features,
      });
      let vectorLayer = new VectorLayer({
        source: vectorSource,
        style: new Style({
          fill: new Fill({
            color: "rgba(255, 255, 255, 0.6)",
          }),
          stroke: new Stroke({
            color: "#319FD3",
            width: 1,
          }),
        }),
      });
      that.map.addLayer(vectorLayer);
    },

    // 获取工程项目信息
    getProjectInfo() {
      this.loading = true;
      listInfo({
        pageNum: 1,
        pageSize: 1000,
        ids: null,
        data: {
          isMajor: null,
          projectName: null,
          unitLeader: null,
          projectLegalPerson: null,
          projectLegalUnit: null,
          projectLegalPhone: null,
          engineeringGrade: null,
          engineeringPurposes: null,
          workCategory: null,
          constructionAddress: null,
          constructionMode: null,
          constructionNature: null,
          constructionContent: null,
          adcd: null,
          basin: null,
          projectType: null,
          // fundingSource: null,

          centralArrangedFunds: null,
          centralArrangedFundsRate: null,
          provincialFunding: null,
          provincialFundingRate: null,
          cityLevelFunds: null,
          cityLevelFundsRate: null,
          countyLevelFunds: null,
          countyLevelFundsRate: null,
          townshipInvestments: null,
          townshipInvestmentsRate: null,

          isMajorProject: null,
          investmentSubject: null,
          constructionPhase: null,
          fundingNumber: null,
          proCode: null,
          proNo: null,
          createUid: null,
          createTime: null,
          updateUid: null,
          updateTime: null,
          owerDept: null,
          isKeyProject: null,
          isPierceProject: null,
          projectKinds: null,
        },
        // 排序方式
        params: {
          // 按哪个字段排序
          orderBy: "create_time",
          // desc降序，升序asc
          sortBy: "desc",
        },
      }).then((response) => {
        console.log("response", response);
        this.ProjectCoordinatePoint(response.records);
      });

      // this.ProjectCoordinatePoint();
    },

    // 回显坐标点
    ProjectCoordinatePoint(data = []) {
      let TestPointVectorSource = new VectorSource({});

      // 处理点数据
      data
        .filter((item) => item.pointLatitudeLongitudeList != null || "")
        .forEach((pointItem) => {
          pointItem.pointLatitudeLongitudeList = JSON.parse(
            pointItem.pointLatitudeLongitudeList
          );
          pointItem.pointLatitudeLongitudeList.forEach((item) => {
            let obj = new Feature({
              geometry: new Point(item),
              pointData: pointItem,
              name: "test",
            });
            TestPointVectorSource.addFeature(obj);
          });
        });

      let TestClusterSource = new Cluster({
        distance: 25,
        source: TestPointVectorSource,
      });
      // 创建一个VectorLayer并使用上面定义的VectorSource
      let TestPointVectorLayer = new VectorLayer({
        // 非聚合点数据源
        // source: that.pointVectorSource,
        // 聚合点数据源
        source: TestClusterSource,
        // 聚合点样式
        style: function (feature, a, b) {
          let ZB =
            feature.values_.features[0].values_.geometry.flatCoordinates[0].toFixed(
              4
            ) +
            "，" +
            feature.values_.features[0].values_.geometry.flatCoordinates[1].toFixed(
              4
            );
          let NO = feature.values_.features.length.toString();
          let resText = NO == "1" ? ZB : NO;
          let offsetY = NO == "1" ? 20 : 0;
          return new Style({
            fill: new Fill({
              color: "rgba(255, 255, 255, 0.2)", // 填充颜色
            }),
            stroke: new Stroke({
              color: "#409eff", // 边框颜色
              width: 4, // 边框宽度
            }),
            image: new Circle({
              radius: 8, // 圆点半径
              fill: new Fill({
                color: "red", // 圆点填充颜色
              }),
            }),
            text: new Text({
              text: resText,
              offsetY: offsetY,
              fill: new Fill({
                color: "yellow",
              }),
            }),
          });
        },
        zIndex: 1,
      });

      this.map.addLayer(TestPointVectorLayer);
    },

    addPopup(evt, evtFeature) {
      // 使用变量存储弹窗所需的 DOM 对象
      var container = document.getElementById("popup");
      var closer = document.getElementById("popup-closer");
      var content = document.getElementById("popup-content");

      // 创建一个 Overlay 对象，并设置其位置和 DOM 对象
      let overlay = new Overlay({
        element: container,
        autoPan: true,
        positioning: "bottom-left",
        stopEvent: true,
        autoPanAnimation: {
          duration: 250,
        },
      });

      // 将 Overlay 添加到地图中
      this.map.addOverlay(overlay);

      let _that = this;
      /**
       * 为弹窗添加一个响应关闭的函数
       */
      closer.onclick = function () {
        content.style.display = "none";
        overlay.setPosition(undefined);
        closer.blur();
        return false;
      };

      this.map.on("singleclick", async (evt) => {
        //判断鼠标是否在要素上
        let feature = evtFeature
          ? evtFeature
          : this.map.forEachFeatureAtPixel(
              evt.pixel,
              function (feature, layer) {
                return feature;
              }
            );

        if (
          feature != undefined &&
          feature.getProperties().features.length > 0
        ) {
          console.log(feature.getGeometry().getType());

          console.log(feature.get("name"));
          if (feature.getProperties().features.length === 1) {
            let data = feature.getProperties().features[0].values_.pointData;

            const contentHtml = `

            <div style="display: flex;flex-direction: column;justify-content: center;align-items: flex-start;">
              <span id='projectName' data-pID='${
                data.id
              }' style='cursor: pointer;'>项目名：${data.projectName}</span>
              <span>项目编码：${data.proCode}</span>
              <span>项目类型：${this.projectTypeFormat(data) || ""}</span>
<span>建设性质：${this.constructionNatureFormat(data)}</span>

              </div>

            `;
            content.innerHTML = contentHtml;
            content.style.display = "block";
            overlay.setPosition(evt.coordinate);
          } else {
            this.$message.warning("请放大精度查看");
            return;
          }
        } else {
          //鼠标没有悬停在要素上
          this.map.getTargetElement().style.cursor = "auto";
          // content.style.display = "none";
          // overlay.setPosition(undefined);
        }
      });
    },

    // 撤销
    handleReturn() {
      console.log("this.all_draw_feature", this.all_draw_feature);

      var pop = this.all_draw_feature.pop();
      console.log("当前图像内容 " + this.all_draw_feature.length, pop);
      if (pop == undefined) {
        // alert("已全部撤销");
        this.$message.warning("已全部撤销");
      } else if (pop[0] === "point") {
        // console.log(
        //   "this.pointVectorLayer",
        //   this.pointVectorLayer.getSource().getSource()
        // );
        // this.pointVectorLayer.getSource().getSource().removeFeature(pop[1]);
        this.pointVectorSource.removeFeature(pop[1]);
        this.all_point_coords.pop();
      } else if (pop[0] === "line") {
        // console.log("this.lineVectorLayer", this.lineVectorLayer.getSource());
        // this.lineVectorLayer.getSource().removeFeature(pop[1]);
        this.lineVectorSource.removeFeature(pop[1]);
        this.all_line_coords.pop();
      }
    },

    // 项目类型字典翻译
    projectTypeFormat(row, column) {
      if (row.isMajor == "zd") {
        return this.selectDictLabel(
          this.zd_projectTypeOptions,
          row.projectType
        );
      } else if (row.isMajor == "ms") {
        return this.selectDictLabel(
          this.ms_projectTypeOptions,
          row.projectType
        );
      } else if (row.isMajor != null) {
        return "其他";
      }
    },
    // 建设性质字典
    constructionNatureFormat(row, column) {
      return this.selectDictLabel(
        this.constructionNatureOptions,
        row.constructionNature
      );
    },

    // 删除
    handleDelect() {
      let that = this;
      let { delBtnDom } = this.resetBtn("del");
      if (delBtnDom.innerHTML === "选择删除") {
        delBtnDom.innerHTML = "取消删除";
        // 创建点选工具
        this.interaction = new Select({
          condition: SingleClick,
          style: new Style({
            image: new Circle({
              radius: 10,
              stroke: new Stroke({
                width: 4,
                color: "red",
              }),
              fill: new Fill({
                color: "green",
              }),
            }),
            stroke: new Stroke({
              width: 4,
              color: "red",
            }),
            fill: new Fill({
              color: "green",
            }),
          }),
          layers: [that.pointVectorLayer, that.lineVectorLayer],
        });
        // 添加单选工具
        this.map.addInteraction(this.interaction);
      } else {
        delBtnDom.innerHTML = "选择删除";
        this.map.removeInteraction(this.interaction);
      }
      // 监听select事件
      this.interaction.on("select", function (e) {
        if (e.selected.length > 0) {
          var feature = e.selected[0];
          var name = feature.get("name");
          console.log("选中的几点", e, feature);
          console.log("this.pointVectorLayer", that.pointVectorSource);
          let no = feature.values_.features
            ? feature.values_.features.length
            : 1;

          console.log("选中个数", no);
          that
            .$confirm("是否删除选中" + no + "个的元素？", "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
            .then(function () {
              that.lineVectorSource.removeFeature(feature);
              that.pointVectorSource.getFeatures().forEach(function (feature1) {
                if (
                  feature1.values_.geometry.flatCoordinates[0] ===
                    feature.values_.geometry.flatCoordinates[0] &&
                  feature1.values_.geometry.flatCoordinates[1] ===
                    feature.values_.geometry.flatCoordinates[1]
                ) {
                  that.pointVectorSource.removeFeature(feature1);
                }
              });
            });
        }
      });
    },

    // 清空绘制图层
    handleClearDrawLayer() {
      this.pointVectorSource.clear();
      this.lineVectorSource.clear();
      this.all_draw_feature = [];
      this.all_point_coords = [];
      this.all_line_coords = [];
    },

    // 保存绘制
    handleSaveCoords() {
      this.all_point_coords = this.pointVectorSource
        .getFeatures()
        .map((item) => item.geometryChangeKey_.target.flatCoordinates);
      if (this.all_point_coords.length == 0 && this.all_line_coords == 0) {
        this.$message.warning("暂无需要保存数据");
        return;
      }

      let lineArr = [];

      let dataArr = this.lineVectorSource.getFeatures();
      dataArr.forEach((item) => {
        let lineItem = [];
        for (
          let i = 0;
          i < item.geometryChangeKey_.target.flatCoordinates.length;
          i += 2
        ) {
          // console.log(88888, this.lineVectorSource.getFeatures());
          lineItem.push(
            item.geometryChangeKey_.target.flatCoordinates.slice(i, i + 2)
          );
        }
        lineArr.push(lineItem);
      });

      this.all_line_coords = lineArr;
      this.all_draw_feature = this.pointVectorSource
        .getFeatures()
        .map((item) => ["point", item])
        .concat(
          this.lineVectorSource.getFeatures().map((item) => ["line", item])
        );
      console.log("保存所有的交互绘制");
      console.log("all_draw_feature", this.all_draw_feature);
      console.log("all_point_coords", this.all_point_coords);
      console.log("all_line_coords", this.all_line_coords);

      // 向父组件传数据
      this.$emit(
        "getMapData",
        this.all_point_coords,
        this.all_line_coords,
        this.all_draw_feature
      );

      // 清除所有
      this.handleClearDrawLayer();
      // 取消绘制,并修改文字
      let pointBtnDom = document.getElementById("drawPointBtn");
      let pointBtnText = pointBtnDom.innerHTML;
      let lineBtnDom = document.getElementById("drawLineBtn");
      let lineBtnText = lineBtnDom.innerHTML;
      if (pointBtnText === "取消绘制点") {
        pointBtnDom.innerHTML = "绘制点";
        this.map.removeInteraction(this.pointDrawFlag);
      }
      if (lineBtnText === "取消绘制线") {
        lineBtnDom.innerHTML = "绘制线";
        this.map.removeInteraction(this.lineDrawFlag);
      }
      // alert("保存成功！");
    },

    // 搜索
    handleSearch(item) {
      let lonRules =
        /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{1,15})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{1,15}|180)$/;
      let latRules =
        /^(\-|\+)?([0-8]?\d{1}\.\d{1,15}|90\.0{1,15}|[0-8]?\d{1}|90)$/;
      if (!lonRules.test(item.lon)) {
        this.$message.warning(
          "请输入正确的经度，例如：-113.27或113.27，小数位数不限"
        );
        return false;
      }
      if (!latRules.test(item.lat)) {
        this.$message.warning(
          "请输入正确的纬度，例如：-23.13或23.13，小数位数不限"
        );
        return false;
      }
      console.log(999, item);

      this.map.getView().setCenter([Number(item.lon), Number(item.lat)]);
      this.map.getView().setZoom(13);
      let features = [];
      let obj = new Feature({
        geometry: new Point([Number(item.lon), Number(item.lat)]),
      });
      // // 点样式
      obj.setStyle(
        new Style({
          text: new Text({
            // text: item[0].toFixed(4) + "，" + item[1].toFixed(4),
            offsetY: 20,
            // font: "12px Calibri,sans-serif",
            fill: new Fill({
              color: "#fff",
            }),
            // stroke: new Stroke({
            //   color: "#f00",
            //   width: 3,
            // }),
          }),
          image: new Circle({
            radius: 8,
            fill: new Fill({
              color: "blue",
            }),
          }),
        })
      );
      features.push(obj);
      // let that = this;
      // let pointVectorSource = new VectorSource({
      //   features,
      // });
      // // console.log(444, this.pointVectorSource);
      // let ClusterSource = new Cluster({
      //   distance: 25,
      //   source: pointVectorSource,
      // });
      // this.pointVectorLayer.getSource().clear();
      // console.log(1111, this.pointVectorLayer.getSource());
      this.pointVectorSource.addFeatures(features);
    },
  },
};
</script>
<style lang="scss" scoped>
#map {
  height: calc(100vh - 242px);
}

.ol-popup {
  position: relative;
  padding: 20px;
  width: 400px;
  height: auto;
  background-color: rgb(255, 255, 255);
  border-radius: 5px;

  .popup-closer {
    cursor: pointer;
    position: absolute;
    top: 5px;
    right: 5px;

    &:hover {
      opacity: 0.6;
    }
  }
}
</style>
