'use strict';

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

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _deepmerge = require('deepmerge');

var _deepmerge2 = _interopRequireDefault(_deepmerge);

var _hat = require('hat');

var _hat2 = _interopRequireDefault(_hat);

var _constants = require('./constants');

var _constants2 = _interopRequireDefault(_constants);

var _to_dense_array = require('./libs/to_dense_array');

var _to_dense_array2 = _interopRequireDefault(_to_dense_array);

var _string_set = require('./libs/string_set');

var _string_set2 = _interopRequireDefault(_string_set);

var _point = require('./feature_types/point');

var _point2 = _interopRequireDefault(_point);

var _line_string = require('./feature_types/line_string');

var _line_string2 = _interopRequireDefault(_line_string);

var _polygon = require('./feature_types/polygon');

var _polygon2 = _interopRequireDefault(_polygon);

var _multi_feature = require('./feature_types/multi_feature');

var _multi_feature2 = _interopRequireDefault(_multi_feature);

var _styles = require('./styles');

var _render = require('./render');

var _render2 = _interopRequireDefault(_render);

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

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

/**
 * @文件说明: 定义Draw绘图的数据存储管理
 * @创建人: pjtools@vip.qq.com
 * @创建时间: 2020-05-26 17:09:58
 */

var Store = function () {
  function Store(ctx) {
    var _this = this;

    (0, _classCallCheck3['default'])(this, Store);

    this.ctx = ctx;
    this.iMapApi = ctx.api.iMapApi;

    // 绘制的Feature要素对象
    this._features = {};
    // 绘制的Feature要素Id集合
    this._featureIds = new _string_set2['default']();
    this._selectedFeatureIds = new _string_set2['default']();
    this._selectedCoordinates = [];
    // 绘制时待更新的Feature要素Id集合
    this._changedFeatureIds = new _string_set2['default']();
    this._deletedFeaturesToEmit = [];
    this._emitSelectionChange = false;

    this.sources = [];
    // 处理绘图的默认数据集
    var featureCollection = this.iMapApi.getFeatureCollection(ctx.options.data);
    if (featureCollection && featureCollection.features.length) {
      featureCollection.features.map(function (f) {
        !f.id && (f.id = (0, _hat2['default'])());
        var feature = _this.getFeatureToGeoJSON(f);
        _this._features[f.id] = feature;
        _this._featureIds.add(feature.id);
        _this.sources.push(feature.toGeoJSON());
      });
    }
    // 合并图层主题样式
    this.theme = (0, _deepmerge2['default'])(_styles.defaultDrawTheme, ctx.options.theme);
    // 判断是否渲染加载绘图图层组
    this._isLoadedLayers = false;
    // 图层数据渲染临时绘制数据
    var renderRequest = void 0;
    this.render = function () {
      if (!renderRequest) {
        renderRequest = requestAnimationFrame(function () {
          renderRequest = null;
          _render2['default'].call(_this);
        });
      }
    };
    // 判断是否为模式切换时渲染状态
    this.isModeChangeRender = false;
  }

  // 判断是否渲染加载矢量图层组


  (0, _createClass3['default'])(Store, [{
    key: 'isLoadedLayers',
    value: function isLoadedLayers() {
      return this._isLoadedLayers;
    }

    // 添加绘图的矢量图层组

  }, {
    key: 'addLayers',
    value: function addLayers() {
      var _this2 = this;

      if (this._isLoadedLayers) {
        return;
      }

      var sourceId = _constants2['default'].sources.ID + '.' + this.ctx.uid;
      var layerGroupId = 'draw-layers-group.' + this.ctx.uid;
      // 添加图层的所属数据源
      this.iMapApi.addSource(sourceId, {
        type: 'geojson',
        data: this.iMapApi.getFeatureCollection(this.sources)
      });
      // 获取绘图的图层结构
      var layers = (0, _styles.getDrawLayers)(this.theme);
      // 添加图层到绘图图层组中
      layers && layers.map(function (layer) {
        var id = layer.id + '.' + _this2.ctx.uid;
        layer.options.source = sourceId;
        switch (layer.type) {
          case 'point':
            {
              _this2.iMapApi.Layers.addCirclePointLayer(id, layer.options, { layerGroupId: layerGroupId });
              break;
            }
          case 'line':
            {
              _this2.iMapApi.Layers.addLineLayer(id, layer.options, { layerGroupId: layerGroupId });
              break;
            }
          case 'polygon':
            {
              _this2.iMapApi.Layers.addPolygonLayer(id, layer.options, { layerGroupId: layerGroupId });
              break;
            }
        }
      });
      // 更新状态
      this._isLoadedLayers = true;
    }

    // 移除绘图的矢量图层组

  }, {
    key: 'removeLayers',
    value: function removeLayers() {
      if (!this._isLoadedLayers) {
        return;
      }
      // 移除绘图图层组
      this.iMapApi.removeLayer('draw-layers-group.' + this.ctx.uid);
      // 更新状态
      this._isLoadedLayers = false;
    }

    // 设置绘图模式切换时渲染状态

  }, {
    key: 'setModeChangeRendering',
    value: function setModeChangeRendering() {
      this.isModeChangeRender = true;
      return this;
    }

    // 转换Feature要素为内置绘图的对象

  }, {
    key: 'getFeatureToGeoJSON',
    value: function getFeatureToGeoJSON(geojson) {
      var feature = null;
      switch (geojson.geometry.type) {
        case _constants2['default'].geojsonTypes.POINT:
          feature = new _point2['default'](this.ctx, geojson);
          break;
        case _constants2['default'].geojsonTypes.LINE_STRING:
          feature = new _line_string2['default'](this.ctx, geojson);
          break;
        case _constants2['default'].geojsonTypes.POLYGON:
          feature = new _polygon2['default'](this.ctx, geojson);
          break;
        case _constants2['default'].geojsonTypes.MULTI_POINT:
        case _constants2['default'].geojsonTypes.MULTI_LINE_STRING:
        case _constants2['default'].geojsonTypes.MULTI_POLYGON:
          feature = new _multi_feature2['default'](this.ctx, geojson);
          break;
      }

      if (feature) {
        var mode = this.ctx.events.currentModeName() || this.ctx.options.defaultMode;
        return feature.internal(mode);
      }
      return feature;
    }

    // 获取指定Id的Feature要素对象

  }, {
    key: 'get',
    value: function get(id) {
      return this._features[id];
    }

    // 获取所有的已渲染的Feature要素Ids

  }, {
    key: 'getAllIds',
    value: function getAllIds() {
      return this._featureIds.values();
    }

    // 获取所有的渲染Feature要素

  }, {
    key: 'getAll',
    value: function getAll() {
      var _this3 = this;

      return Object.keys(this._features).map(function (id) {
        return _this3._features[id];
      });
    }

    // 获取所有待更新的Feature要素Ids

  }, {
    key: 'getChangedIds',
    value: function getChangedIds() {
      return this._changedFeatureIds.values();
    }

    // 清空更新绘图的Feature要素Id记录器

  }, {
    key: 'clearChangedIds',
    value: function clearChangedIds() {
      this._changedFeatureIds.clear();
      return this;
    }

    // 设置指定的Feature要素Id添加到更新状态

  }, {
    key: 'featureChanged',
    value: function featureChanged(featureId) {
      this._changedFeatureIds.add(featureId);
      return this;
    }

    // 获取所有选中Feature要素的Id集合

  }, {
    key: 'getSelectedIds',
    value: function getSelectedIds() {
      return this._selectedFeatureIds.values();
    }

    // 获取所有选中的Feature要素集合

  }, {
    key: 'getSelected',
    value: function getSelected() {
      var _this4 = this;

      return this._selectedFeatureIds.values().map(function (id) {
        return _this4.get(id);
      });
    }

    // 清除当前选中的要素

  }, {
    key: 'clearSelected',
    value: function clearSelected() {
      var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      this.deselect(this._selectedFeatureIds.values(), { silent: options.silent });
      return this;
    }

    // 选中指定的Feature要素

  }, {
    key: 'select',
    value: function select(featureIds) {
      var _this5 = this;

      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      (0, _to_dense_array2['default'])(featureIds).map(function (id) {
        if (_this5._selectedFeatureIds.has(id)) return;
        _this5._selectedFeatureIds.add(id);
        _this5._changedFeatureIds.add(id);
        if (!options.silent) {
          _this5._emitSelectionChange = true;
        }
      });
      return this;
    }

    // 删除当前选中指定Id的Feature要素

  }, {
    key: 'deselect',
    value: function deselect(featureIds) {
      var _this6 = this;

      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      (0, _to_dense_array2['default'])(featureIds).map(function (id) {
        if (!_this6._selectedFeatureIds.has(id)) {
          return;
        }
        _this6._selectedFeatureIds['delete'](id);
        _this6._changedFeatureIds.add(id);
        if (!options || !(0, _methodsUtil.isBooleanTrue)(options.silent)) {
          _this6._emitSelectionChange = true;
        }
      });
      this.refreshSelectedCoordinates(options);
      return this;
    }

    // 设置指定的Id的要素选中

  }, {
    key: 'setSelected',
    value: function setSelected(featureIds) {
      var _this7 = this;

      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      featureIds = (0, _to_dense_array2['default'])(featureIds);
      // 将指定Id要素数据之外的选中要素进行移除
      this.deselect(this._selectedFeatureIds.values().filter(function (id) {
        return featureIds.indexOf(id) === -1;
      }), { silent: options.silent });
      // 选中指定Id的要素
      this.select(featureIds.filter(function (id) {
        return !_this7._selectedFeatureIds.has(id);
      }), { silent: options.silent });
      return this;
    }

    // 判断指定Id的要素是否选中

  }, {
    key: 'isSelected',
    value: function isSelected(featureId) {
      return this._selectedFeatureIds.has(featureId);
    }

    // 刷新选中Feature要素的节点坐标

  }, {
    key: 'refreshSelectedCoordinates',
    value: function refreshSelectedCoordinates() {
      var _this8 = this;

      var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      var newSelectedCoordinates = this._selectedCoordinates.filter(function (point) {
        return _this8._selectedFeatureIds.has(point.feature_id);
      });
      if (this._selectedCoordinates.length !== newSelectedCoordinates.length && (!options || !(0, _methodsUtil.isBooleanTrue)(options.silent))) {
        this._emitSelectionChange = true;
      }
      this._selectedCoordinates = newSelectedCoordinates;
    }

    // 获取选中Feature要素的节点坐标

  }, {
    key: 'getSelectedCoordinates',
    value: function getSelectedCoordinates() {
      var _this9 = this;

      var selected = this._selectedCoordinates.map(function (coordinate) {
        var feature = _this9.get(coordinate.feature_id);
        return {
          coordinates: feature.getCoordinate(coordinate.coord_path),
          path: coordinate.coord_path,
          pid: coordinate.feature_id
        };
      });
      return selected;
    }

    // 设置选中的Feature要素节点

  }, {
    key: 'setSelectedCoordinates',
    value: function setSelectedCoordinates(coordinates) {
      this._selectedCoordinates = coordinates;
      this._emitSelectionChange = true;
      return this;
    }

    // 清空选中的Feauture要素节点

  }, {
    key: 'clearSelectedCoordinates',
    value: function clearSelectedCoordinates() {
      this._selectedCoordinates = [];
      this._emitSelectionChange = true;
      return this;
    }

    // 添加绘制Feature要素

  }, {
    key: 'add',
    value: function add(feature) {
      this._features[feature.id] = feature;
      this._featureIds.add(feature.id);
      this.featureChanged(feature.id);
      return this;
    }

    // 删除绘制的Feature要素

  }, {
    key: 'delete',
    value: function _delete(featureIds) {
      var _this10 = this;

      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      (0, _to_dense_array2['default'])(featureIds).map(function (id) {
        if (!_this10._featureIds.has(id)) return;
        _this10._featureIds['delete'](id);
        _this10._selectedFeatureIds['delete'](id);
        // 将Meta为Feature要素的数据加入待删除的队列
        if (_this10._deletedFeaturesToEmit.indexOf(_this10._features[id]) === -1 && _this10._features[id].properties['draw:meta'] === _constants2['default'].meta.FEATURE) {
          !options.silent && _this10._deletedFeaturesToEmit.push(_this10._features[id]);
        }
        delete _this10._features[id];
      });
      this.refreshSelectedCoordinates(options);
      return this;
    }

    // 设置Feature的外置属性

  }, {
    key: 'setFeatureProperty',
    value: function setFeatureProperty(featureId, property, value) {
      this.get(featureId).setProperty(property, value);
      this.featureChanged(featureId);
    }

    // 创建延迟渲染函数

  }, {
    key: 'createRenderBatch',
    value: function createRenderBatch() {
      var _this11 = this;

      var holdRender = this.render;
      var numRenders = 0;
      this.render = function () {
        numRenders++;
      };

      return function () {
        _this11.render = holdRender;
        if (numRenders > 0) {
          _this11.render();
        }
      };
    }
  }]);
  return Store;
}();

exports['default'] = Store;