import {uuid} from '@/utils';

export default {
  data() {
    return {
      polyLayer: null,
      layerId: 'vl',
    };
  },
  mounted() {
    this.layerId = uuid();
    if (!this.polyLayer) {
      this.polyLayer = new BDLayers.Lib.Layer.CBVectorLayer(
        `poly_layer${this.layerId}`, {enableAltitude: true});
      window.map.addCustomLayers(this.polyLayer, 1);
    }
  },
  methods: {
    drawPoly({
               name = '多边形',
               coordinates,
               altitude = 0,
               symbol = {},
               bizAttr = {},
               labelSymbol = {},
               polyOnClick = () => {
               },
             }, polyLayer) {
      const polygonId = `auto_poly_id${uuid()}`;
      let symbolParam = {
        lineColor: '#34495e',
        lineWidth: 2,
        polygonFill: '#1bbc9b',
        polygonOpacity: 0.4,
      };
      let labelSymbolParam = {
        labelText: name,
        labelTextColor: '#fefefe',
        labelTextSize: 15,
      };
      Object.assign(labelSymbolParam, labelSymbol);
      Object.assign(symbolParam, symbol);
      const polygon = new BDLayers.Lib.Overlays.Polygon('p1', {
        coordinates: coordinates,
        altitude,
        symbol: symbolParam,
        labelSymbol: labelSymbolParam,
        bizAttr: {...bizAttr, polygonId},
      });
      //多边形的点击事件
      polygon.on('click', polyOnClick);
      if (!polyLayer) {
        this.polyLayer.addGeometry(polygon);
      } else {
        polyLayer.addGeometry(polygon);
      }
      return polygon;
    },
    polygonToCoordinates(polygon) {
      // 正则表达式匹配坐标点
      const regex = /(-?\d+(\.\d+)?\s-?\d+(\.\d+)?)/g;
      const matches = polygon.match(regex);
      if (matches && matches.length > 0) {
        return matches
          .map(point => {
            const [x, y] = point.trim().split(' ').map(Number);
            return [x, y];
          });
      }
      return [];
    },
    createLayer(mapIns, zIndex = 1) {
      const uid = uuid();
      const layerId = `poly_layer${uid}`;
      const polyLayer = new BDLayers.Lib.Layer.CBVectorLayer(
        layerId, {enableAltitude: true});
      polyLayer.cust = {
        layerId: uid,
        mapIns,
        clearLayer: (layer) => {
          mapIns.removeLayersById(layerId);
        }
      }
      mapIns.addCustomLayers(polyLayer, zIndex);
      return polyLayer;
    },
    clearLayer(layer) {
      if (layer) {
        layer.removeAll();
        return;
      }
      this.polyLayer && this.polyLayer.removeAll();
    },
    destroyLayer(layerId, mapIns) {
      layerId && mapIns.removeLayersById(layerId)
    },
  },
  beforeDestroy() {
    this.polyLayer && window.map.removeLayersById(`poly_layer${this.layerId}`);
  },
};
