'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _methodsUtil = require('../../_util/methods-util');

var _find = require('lodash/find');

var _find2 = _interopRequireDefault(_find);

var _findIndex = require('lodash/findIndex');

var _findIndex2 = _interopRequireDefault(_findIndex);

var _remove = require('lodash/remove');

var _remove2 = _interopRequireDefault(_remove);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

/**
 * @文件说明: 构建Map地图的“图层”管理函数方法
 * @创建人: pjtools@vip.qq.com
 * @创建时间: 2020-03-21 14:41:01
 */

var layer = {
  /**
   * 获取原生Mapbox GL的所有图层对象
   */
  getMapboxLayers: function getMapboxLayers() {
    var mapStyle = this.map.getStyle();
    return mapStyle && mapStyle.layers || [];
  },


  /**
   * 获取指定Id的图层(组)的对象
   * @param {String} id 图层Id名称
   * @param {String} layerGroupId 选填项，所属图层组Id名称
   */
  getLayer: function getLayer(id) {
    var layerGroupId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;

    // 判断是否有图层组Id
    if (layerGroupId) {
      var layersGroup = this._mapLayers[layerGroupId];
      // 判断是否有图层组的图层数组集合对象
      if (layersGroup && (0, _methodsUtil.isBooleanTrue)(layersGroup.isLayerGroup) && (0, _methodsUtil.isNotEmptyArray)(layersGroup.layers)) {
        // 在图层组的数组图层集合中过滤指定Id的图层对象
        var _layer = (0, _find2['default'])(layersGroup.layers, { id: id });
        if (_layer) {
          return _layer;
        }
      }
    } else {
      if (this._mapLayers[id]) {
        return this._mapLayers[id];
      }
    }
    return null;
  },


  /**
   * 添加MapboxGL Layer图层对象到地图Map中
   * @param {Layer} layer 待添加的MapboxGL的Layer图层对象
   * @param {String} beforeId 待添加到指定图层(组)Id之前
   */
  addLayer: function addLayer(layer) {
    var beforeId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;

    if (!layer.id || this.getLayer(layer.id)) {
      !layer.id && console.error('图层Layer对象缺少[id]必须设定属性.');
      return;
    }

    // 特殊处理矢量瓦片VTS服务图层
    if (layer.type && layer.type === 'VTS') {
      return this.addLayerToGroup(layer.id, layer, beforeId);
    } else {
      // 添加图层的数据源
      var currentSource = null;
      if (layer.source) {
        if (typeof layer.source !== 'string') {
          var sourceId = layer.source && layer.source.id ? layer.source.id : layer.id;
          currentSource = this.addSource(sourceId, layer.source);
          layer.source = currentSource.id;
        } else {
          currentSource = this.getSource(layer.source);
        }
      }
      // 添加到地图Map中
      if (beforeId) {
        this.map.addLayer(layer, beforeId);
      } else {
        this.map.addLayer(layer);
      }
      var currentLayer = this.map.getLayer(layer.id);
      currentLayer.isLayerGroup = false;
      // 存储当前图层对象
      this._mapLayers[layer.id] = currentLayer;
      this._mapLayersIds.push(layer.id);
      // 存储数据源的所属图层Id
      if (currentSource) {
        !currentSource._layersIds && (currentSource._layersIds = []);
        currentSource._layersIds.indexOf(layer.id) === -1 && currentSource._layersIds.push(layer.id);
      }
      return currentLayer;
    }
  },


  /**
   * 添加MapboxGL Layer图层集合到地图Map中
   * @param {Array} layers 待添加的MapboxGL的Layer图层的数组集合
   * @param {String} beforeId 待添加到指定图层(组)Id之前
   */
  addLayers: function addLayers(layers) {
    var _this = this;

    var beforeId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;

    if (!(0, _methodsUtil.isNotEmptyArray)(layers)) {
      console.error('待添加的图层集合不是一个有效的数组对象.');
      return;
    }
    return layers.map(function (layer) {
      return _this.addLayer(layer, beforeId);
    });
  },


  /**
   * 删除指定Id名称的图层对象
   * @param {String} id 图层Id名称
   */
  removeLayer: function removeLayer(id) {
    var _this2 = this;

    var layer = this.getLayer(id);
    if (layer) {
      // 移除图层和数据源
      var deleteLayer = function deleteLayer(currentLayer) {
        // 移除图层的绑定事件
        currentLayer.eventIds && _this2.off(currentLayer.eventIds);
        // 移除图层对象
        _this2.map.removeLayer(currentLayer.id);
        // 移除图层数据源
        _this2.removeSource(currentLayer.source);
      };

      // 判断是否为图层组对象
      if (this.isLayerGroup(id)) {
        layer.layers.map(function (currentLayer) {
          deleteLayer(currentLayer);
        });
        // 移除当前图层对象的缓存
        delete this._mapLayers[id];
        (0, _remove2['default'])(this._mapLayersIds, function (item) {
          return !!(item.layerGroupId && item.layerGroupId === id);
        });
      } else {
        deleteLayer(layer);
        // 移除当前图层对象的缓存
        delete this._mapLayers[id];
        this._mapLayersIds.splice(this._mapLayersIds.indexOf(id), 1);
      }
    } else {
      console.error('\u56FE\u5C42Id\uFF1A[' + id + ']\u5BF9\u8C61\u4E0D\u5B58\u5728\u6216\u56FE\u5C42\u7EC4\u4E2D\u56FE\u5C42\u8BF7\u4F7F\u7528[removeLayerToGroup]\u51FD\u6570\u65B9\u6CD5.');
    }
  },


  /**
   * 删除指定Id数组集合的图层对象
   * @param {Array} layersId 图层Id数组集合
   */
  removeLayers: function removeLayers(layersId) {
    if ((0, _methodsUtil.isArray)(layersId)) {
      for (var i = layersId.length - 1; i >= 0; i--) {
        this.removeLayer(layersId[i]);
      }
    } else {
      console.log('\u56FE\u5C42Id\u96C6\u5408\u5FC5\u987B\u662F\u4E00\u4E2A\'String[]\'\u5B57\u7B26\u578B\u6570\u7EC4\u683C\u5F0F.');
    }
  },


  /**
   * 移动指定Id的图层(组)内到的beforeId图层(组)之前
   * @param {String} id 图层(组)的Id名称
   * @param {String} beforeId 待移动到指定图层Id之前
   */
  moveLayer: function moveLayer(id, beforeId) {
    var _this3 = this;

    var layer = this.getLayer(id);
    if (!layer) {
      return;
    }

    var isLayerGroup = this.isLayerGroup(id);
    var layerIndex = isLayerGroup ? (0, _findIndex2['default'])(this._mapLayersIds, { layerGroupId: id }) : this._mapLayersIds.indexOf(id);
    // 判断是否指定移动前置图层Id，如果无指定则移动地图图层的最后
    if (!beforeId) {
      var lastIndex = this._mapLayersIds.length - 1;
      // 移动图层顺序
      if (isLayerGroup) {
        layer.layers.map(function (layerItem) {
          _this3.map.moveLayer(layerItem.id);
        });
      } else {
        this.map.moveLayer(id);
      }
      // 调整图层对象的缓存的顺序
      this._mapLayersIds.splice(lastIndex + 1, 0, this._mapLayersIds[layerIndex]);
      this._mapLayersIds.splice(layerIndex, 1);
    } else {
      var isBeforeLayerGroup = this.isLayerGroup(beforeId);
      var newBeforeId = null;
      var beforeIndex = null;
      // beforeId判断是否为图层组，则重算图层组的图层Id
      if (isBeforeLayerGroup) {
        var firstLayer = this.getGroupFirstLayer(beforeId);
        newBeforeId = firstLayer.id;
        beforeIndex = (0, _findIndex2['default'])(this._mapLayersIds, { layerGroupId: beforeId });
      } else {
        newBeforeId = beforeId;
        beforeIndex = this._mapLayersIds.indexOf(beforeId);
      }
      // 移动图层顺序
      if (isLayerGroup) {
        layer.layers.map(function (layerItem) {
          _this3.map.moveLayer(layerItem.id, newBeforeId);
        });
      } else {
        this.map.moveLayer(id, newBeforeId);
      }
      // 调整图层对象的缓存的顺序
      this._mapLayersIds.splice(beforeIndex, 0, this._mapLayersIds[layerIndex]);
      this._mapLayersIds.splice(layerIndex < beforeIndex ? layerIndex : layerIndex + 1, 1);
    }
  },


  /**
   * 向上移动一层指定Id的图层(组)
   * @param {String} id 图层(组)的Id名称
   */
  moveUpLayer: function moveUpLayer(id) {
    var layer = this.getLayer(id);
    if (!layer) {
      return;
    }
    var isLayerGroup = this.isLayerGroup(id);
    // 计算当前图层的索引位置
    var layerIndex = null;
    if (isLayerGroup) {
      layerIndex = (0, _findIndex2['default'])(this._mapLayersIds, { layerGroupId: id });
    } else {
      layerIndex = this._mapLayersIds.indexOf(id);
    }
    // 判断是否已经是顶级层级
    if (layerIndex > 0) {
      var prevlayerItem = this._mapLayersIds[layerIndex - 1];
      var beforeId = prevlayerItem.layerGroupId || prevlayerItem;
      // 向上移动一层
      this.moveLayer(id, beforeId);
    }
  },


  /**
   * 向下移动一层指定Id的图层(组)
   * @param {String} id 图层(组)的Id名称
   */
  moveDownLayer: function moveDownLayer(id) {
    var layer = this.getLayer(id);
    if (!layer) {
      return;
    }
    var nextlayerId = this.getNextLayerId(id);
    // 判断是否有下一个，则表示当前图层(组)不在最底部
    if (nextlayerId) {
      var beforeId = this.getNextLayerId(nextlayerId);
      // 向下移动一层
      this.moveLayer(id, beforeId);
    }
  },


  /**
   * 获取指定Id的图层(组)的下一个图层对象Id名称
   * @param {String} id 图层Id名称
   */
  getNextLayerId: function getNextLayerId(id) {
    var nextLayerItem = null;
    // 判断是否为图层组
    if (this.isLayerGroup(id)) {
      var layerGroupIndex = (0, _findIndex2['default'])(this._mapLayersIds, { layerGroupId: id });
      nextLayerItem = this._mapLayersIds[layerGroupIndex + 1] || null;
    } else {
      var layerIndex = this._mapLayersIds.indexOf(id);
      if (layerIndex !== -1) {
        nextLayerItem = this._mapLayersIds[layerIndex + 1] || null;
      }
    }

    return nextLayerItem ? nextLayerItem.layerGroupId || nextLayerItem : null;
  },


  /**
   * 设置指定Id的图层(组)的显示/隐藏的状态
   * @param {String} id 图层(组)Id名称
   * @param {Boolean} visible 图层显隐状态
   * @param {String} layerGroupId 选填项，所属图层组Id名称
   */
  setLayerVisibility: function setLayerVisibility(id) {
    var _this4 = this;

    var visible = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
    var layerGroupId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

    var layers = [];
    // 判断是否指定图层组对象，则只获取图层组内的图层对象
    if (layerGroupId) {
      var _layer2 = this.getLayer(id, layerGroupId);
      _layer2 && layers.push(_layer2);
    } else {
      var _layer3 = this.getLayer(id);
      if (_layer3) {
        if (this.isLayerGroup(id)) {
          _layer3.layers.map(function (item) {
            layers.push(item);
          });
        } else {
          layers.push(_layer3);
        }
      }
    }
    // 设置图层的显隐状态
    var visibleValue = (0, _methodsUtil.isBooleanFlase)(visible) ? 'none' : 'visible';
    layers && layers.length && layers.map(function (layer) {
      // 判断是否为VTS矢量瓦片服务图层，且服务加载的默认状态为隐藏，则跳过不设置
      if (!(visibleValue === 'visible' && layer.metadata && layer.metadata.type === 'VTS' && layer.metadata.visibility === 'none')) {
        // 防止图层强制刷新渲染
        var currentLayerVisibility = _this4.map.getLayoutProperty(layer.id, 'visibility') || 'visible';
        if (currentLayerVisibility !== visibleValue) {
          _this4.map.setLayoutProperty(layer.id, 'visibility', visibleValue);
        }
      }
    });
  },


  /**
   * 设置指定Id的栅格类型图层(组)的透明度
   * @param {String} id 图层(组)Id名称
   * @param {Number} opacity 图层的不透明度，范围：0-1
   * @param {String} layerGroupId 选填项，所属图层组Id名称
   */
  setRasterLayerOpacity: function setRasterLayerOpacity(id) {
    var _this5 = this;

    var opacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
    var layerGroupId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

    opacity = (0, _methodsUtil.isNumeric)(opacity) ? Number(opacity) : 1;
    if (opacity > 1) {
      opacity = 1;
    } else if (opacity < 0) {
      opacity = 0;
    }

    var layers = [];
    // 判断是否指定图层组对象，则只获取图层组内的图层对象
    if (layerGroupId) {
      var _layer4 = this.getLayer(id, layerGroupId);
      _layer4 && _layer4.type === 'raster' && layers.push(_layer4);
    } else {
      var _layer5 = this.getLayer(id);
      if (_layer5 && this.isLayerGroup(id)) {
        _layer5.layers.map(function (item) {
          item.type === 'raster' && layers.push(item);
        });
      } else if (_layer5) {
        _layer5.type === 'raster' && layers.push(_layer5);
      }
    }

    layers && layers.length && layers.map(function (layer) {
      // 防止图层强制刷新渲染
      var currentOpacity = _this5.map.getPaintProperty(layer.id, 'raster-opacity') || 1;
      if (currentOpacity !== opacity) {
        _this5.map.setPaintProperty(layer.id, 'raster-opacity', opacity);
      }
    });
  },


  /**
   * 设置指定Id图层(组)的最小与最大层级的区间渲染范围
   * @param {String} id 图层(组)Id名称
   * @param {Number} minzoom 图层最小层级
   * @param {Number} maxzoom 图层最大层级
   * @param {String} layerGroupId 选填项，所属图层组Id名称
   */
  setLayerZoomRange: function setLayerZoomRange(id) {
    var minzoom = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;

    var _this6 = this;

    var maxzoom = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 24;
    var layerGroupId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;

    // 修复最小最大层级范围
    minzoom < 0 && (minzoom = 0);
    maxzoom > 24 && (maxzoom = 24);
    maxzoom < minzoom && (maxzoom = minzoom);

    // 判断是否指定图层组对象，则只获取图层组内的图层对象
    if (layerGroupId) {
      var _layer6 = this.getLayer(id, layerGroupId);
      _layer6 && this.map.setLayerZoomRange(_layer6.id, minzoom, maxzoom);
    } else {
      var _layer7 = this.getLayer(id);
      if (_layer7 && this.isLayerGroup(id)) {
        _layer7.layers.map(function (item) {
          _this6.map.setLayerZoomRange(item.id, minzoom, maxzoom);
        });
      } else if (_layer7) {
        this.map.setLayerZoomRange(_layer7.id, minzoom, maxzoom);
      }
    }
  },


  /**
   * 根据屏幕坐标查询图层的Feature要素
   * @param {String} id 图层(组)Id名称
   * @param {Point} point 查询的几何屏幕坐标，可为单点和BBox范围
   * @param {Object} options 查询的参数条件
   * @param {String} layerGroupId 选填项，所属图层组Id名称
   */
  queryRenderedFeatures: function queryRenderedFeatures(id, point) {
    var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    var layerGroupId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;

    !options.layers && (options.layers = []);
    // 判断是否指定图层组对象，则只获取图层组内的图层对象
    if (layerGroupId) {
      var _layer8 = this.getLayer(id, layerGroupId);
      options.layers.push(_layer8.id);
    } else {
      var _layer9 = this.getLayer(id);
      if (_layer9 && this.isLayerGroup(id)) {
        var _options$layers;

        var layerIds = this.getLayerGroupByIds(id);
        (_options$layers = options.layers).push.apply(_options$layers, (0, _toConsumableArray3['default'])(layerIds));
      } else if (_layer9) {
        options.layers.push(_layer9.id);
      }
    }
    return point && options.layers && this.map.queryRenderedFeatures(point, options);
  }
};

exports['default'] = layer;