import DataUtils from '../utils/DataUtils';
import VerifyUtils from '../utils/VerifyUtils';
import MapProvider from '../geog/MapProvider';
import LayerProvider from '../geog/LayerProvider';
import GeoJsonProvider from '../geog/GeoJsonProvider';

/**
 * 定义统计圆点位图层
 * @alias StatsCircleLayer
 *
 * @summary <用于统计圆点位图层加载>
 */
export default class StatsCircleLayer {
  /**
   * 构造函数
   * @param {Object} options -图层选项
   */
  constructor(options) {
    // 默认数据源ID
    this._defaultSourceId = 'circle_stats';
    // 数据源是否存在
    this._hasSource = true;

    /**
     * 地图对象
     * @type {Object}
     */
    this._map = options.map;

    /**
     * 最小缩放层级
     * @type {Number}
     */
    this._minzoom = DataUtils.default(options.minzoom, 10);

    /**
     * 字段名
     * @type {String}
     */
    this._fieldName = DataUtils.default(options.field, undefined);

    /**
     * 过滤条件数组
     * @type {Array}
     */
    this._filter = DataUtils.default(options.filter, undefined);

    /**
     * 图层服务地址
     * @type {String}
     */
    this._dataUrl = DataUtils.default(options.dataUrl, undefined);

    /**
     * 数据源ID
     * @type {String}
     */
    this._sourceId = DataUtils.default(options.sourceId, this._defaultSourceId);

    /**
     * 图层ID
     * @type {String}
     */
    this._layerId = DataUtils.default(options.layerId, this._sourceId);
    // 标注图层ID
    this._labelLayerId = this._layerId + '-label';

    // 事件
    this._enterEvent = null;
    this._leaveEvent = null;
    this._clickEvent = null; // 外部实现单击事件
    // 初始化鼠标事件
    this._initEvent();
  }

  /** 公有方法 **/
  /**
   * 设置数据
   * @param {Object|String|Array} data -GeoJSON要素集/查询语句/过滤条件(点位)数组
   *
   * @summary <data参数：
   *   Object - GeoJson要素/要素集
   *   String - cql_filter查询语句
   *   Array - 图层过滤条件数组(如：['==', field, value]) or 点位数组(包含longitude, latitude字段)
   * >
   */
  setData(data) {
    // 加载图层
    if (!this.hasLayer()) {
      this.loadLayer();
    }
    // 隐藏图层
    this.showLayer(false);

    let fc = null;
    if (VerifyUtils.isGeoJsonFC(data)) {
      // GeoJSON要素集合
      fc = data;
    } else if (VerifyUtils.isGeoJsonFeature(data)) {
      // GeoJSON要素
      fc = GeoJsonProvider.getEmptyFC();
      fc.features = [data];
    } else if (VerifyUtils.isArray(data)) {
      if (data.length > 1 && VerifyUtils.isString(data[0])) {
        // 设置筛选器
        this._map.setFilter(this._layerId, data);
        this._map.setFilter(this._labelLayerId, data);
      } else {
        // 数组转GeoJSON对象
        fc = GeoJsonProvider.data2PointFC(data);
      }
    } else if (VerifyUtils.isString(data)) {
      // 查询语句
      if (this._hasSource) {
        const source = this._map.getSource(this._sourceId);
        fc = source._data + (data ? "&cql_filter=" + data : '');
      }
    }

    fc = fc || GeoJsonProvider.getEmptyFC();

    // 更新数据源
    this._map.getSource(this._sourceId).setData(fc);
    // 显示图层
    this.showLayer(true);
  }

  /**
   * 加载图层
   */
  loadLayer() {
    if (this.hasLayer()) return;

    const map = this._map;
    const minZoom = this._minzoom;
    const maxZoom = map.getMaxZoom();

    const sourceId = this._sourceId;

    // 判断数据源是否存在
    this._hasSource = LayerProvider.hasSource(map, sourceId);
    if (!this._hasSource) {
      // 添加数据源
      map.addSource(sourceId, {
        type: "geojson",
        data: this._dataUrl || GeoJsonProvider.getEmptyFC()
      });
    }

    // 添加点位圆图层
    map.addLayer({
      type: "circle",
      id: this._layerId,
      source: sourceId,
      minzoom: minZoom,
      layout: {
        visibility: "none",
      },
      paint: {
        "circle-radius": [
          "interpolate", ["linear"], ["zoom"],
          minZoom, 24,
          maxZoom, 120
        ],
        "circle-color": "#176BC9",
        "circle-opacity": 0.8,
        "circle-stroke-width": 2,
        "circle-stroke-color": "#78B7FF"
      }
    }, map._build3dLayerId);

    // 自定义字体颜色
    let textColor = map._customStyle ? map._customStyle.textColor : '#F8F8FF';

    // 添加注记图层
    map.addLayer({
      type: "symbol",
      id: this._labelLayerId,
      source: sourceId,
      minzoom: minZoom,
      layout: {
        "symbol-placement": "point",
        "symbol-avoid-edges": true,
        "icon-allow-overlap": true,
        "text-allow-overlap": true,
        "text-ignore-placement": true,
        "text-line-height": 1.2,
        "text-max-angle": 38,
        "text-offset": [0, 0],
        "text-field": "{" + this._fieldName + "}",
        "text-size": [
          "interpolate", ["linear"], ["zoom"],
          minZoom, 16,
          maxZoom, 44
        ],
        "text-font": ["Microsoft YaHei"],
        "text-max-width": 8,
        visibility: "none"
      },
      paint: {
        "text-color": textColor,
        "text-halo-color": "#8B8B8B",
        "text-halo-width": 0.1,
        "text-halo-blur": 0.5
      }
    });
    // 设置筛选器
    if (this._filter) {
      map.setFilter(this._layerId, this._filter);
      map.setFilter(this._labelLayerId, this._filter);
    }

    // 绑定事件
    this._onEvent();
  }

  /**
   * 显示/隐藏图层
   * @param {Boolean} show -是否显示
   */
  showLayer(show) {
    const map = this._map;

    LayerProvider.showLayer(map, this._layerId, show);
    LayerProvider.showLayer(map, this._labelLayerId, show);
  }

  /**
   * 判断图层是否已加载
   *
   * @returns {Boolean}
   */
  hasLayer() {
    const map = this._map;

    return (
      LayerProvider.hasLayer(map, this._layerId) &&
      LayerProvider.hasLayer(map, this._labelLayerId)
    );
  }


  /**
   * 移除图层
   */
  removeLayer() {
    const map = this._map;

    // 解除事件绑定
    this.offEvent();

    LayerProvider.removeLayer(map, this._layerId);
    LayerProvider.removeLayer(map, this._labelLayerId);
  }

  /**
   * 移除数据源
   */
  removeSource() {
    LayerProvider.removeSource(this._map, this._sourceId);
  }

  /**
   * 绑定单击事件
   * @param {Function} event -事件函数
   */
  onClick(event) {
    this._clickEvent = event;
    if (this.hasLayer()) {
      LayerProvider.onEvent(this._map, this._layerId, 'click', event);
    }
  }

  /**
   * 绑定事件
   * @param {String} name -事件名称
   * @param {Function} event -事件函数
   *
   * @summary <name参数取值：mouseenter-鼠标移入; mouseleave-鼠标移除; click-鼠标单击>
   */
  onEvent(name, event) {
    switch (name) {
      case 'mouseenter': {
        this._enterEvent = event;
        break;
      }
      case 'mouseleave': {
        this._leaveEvent = event;
        break;
      }
      case 'click': {
        this._clickEvent = event;
        break;
      }
      default:
        return;
    }

    if (this.hasLayer()) {
      LayerProvider.onEvent(this._map, this._layerId, name, event);
    }
  }

  /**
   * 解除事件绑定
   */
  offEvent() {
    if (!this.hasLayer()) return;

    const map = this._map;
    let layerId = this._layerId;

    LayerProvider.offEvent(map, layerId, 'mouseenter', this._enterEvent);
    LayerProvider.offEvent(map, layerId, 'mouseleave', this._leaveEvent);
    if (this._clickEvent) {
      LayerProvider.offEvent(map, layerId, 'click', this._clickEvent);
    }
  }

  /** 私有方法 **/
  /**
   * 初始化鼠标事件
   */
  _initEvent() {
    const map = this._map;

    // 移入事件
    this._enterEvent = (e) => {
      MapProvider.setCursor(map, 'pointer');
    }
    // 移出事件
    this._leaveEvent = (e) => {
      MapProvider.setCursor(map);
    }
  }

  /**
   * 绑定事件
   */
  _onEvent() {
    const map = this._map;
    const layerId = this._layerId;

    // 绑定事件
    LayerProvider.onEvent(map, layerId, 'mouseenter', this._enterEvent);
    LayerProvider.onEvent(map, layerId, 'mouseleave', this._leaveEvent);
    if (this._clickEvent) {
      LayerProvider.onEvent(map, layerId, 'click', this._clickEvent);
    }
  }
}
