import DataUtils from "../utils/DataUtils";
import GeogUtils from "../utils/GeogUtils";
import GeoJsonProvider from "../geog/GeoJsonProvider";

import DrainageUnitlineLayer from "./DrainageUnitlineLayer";
import DrainageUnitFlowLayer from "./DrainageUnitFlowLayer";

/**
 * 定义排水单元排水户连接图层提供类
 *
 * @alias DrainageUnitlineProvider
 */
export default class DrainageUnitlineProvider {
  /**
   * 构造函数
   * @param {Object} options -图层选项
   */
  constructor(options) {
    /**
     * 地图对象
     * @type {Object}
     */
    this._map = options.map;

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

    /* 图层对象 */
    this._lineLayer = null;      // 排水单元排水户连接
    this._flowLayer = null;      // 流向
     // 线中心点要素集
     this._centerPointFC = GeoJsonProvider.getEmptyFC();

    // 初始化图层
    this._initLayers();
  }

  /** 公有方法 **/
  /**
   * 设置数据
   * @param {Array|Object} data -数据
   */
  setData(data = null) {
    this._lineLayer.setData(data);
    const centerFC = this._centerPointFC;
    centerFC.features = data.features.map((fea) => {
      // 获取线中点要素
      const coordinates = GeogUtils.calcCenter(fea);
      // 计算线的方位角
        let coordsLen = fea.geometry.coordinates.length;
        let startLonLat = fea.geometry.coordinates[0];
        let endLonLat = fea.geometry.coordinates[coordsLen - 1];
        // 计算方位角
        fea.properties.bearing = GeogUtils.bearing(startLonLat, endLonLat);

      return GeoJsonProvider.getPointFeature(coordinates, fea.properties);
    });
    this._flowLayer.setData(centerFC);
  }

  /**
   * 设置过滤器
   * @param {Array} filter -过滤器
   */
  setFilter(filter) {
    this._lineLayer.setFilter(filter);
    this._flowLayer.setFilter(filter);
  }

  /**
   * 加载图层
   */
  loadLayer() {

    this._lineLayer.loadLayer();
    this._flowLayer.loadLayer();
  }

  /**
   * 显示/隐藏图层
   * @param {Boolean} isShow -是否显示图层
   */
  showLayer(isShow) {
    this._lineLayer.showLayer(isShow);
    this._flowLayer.showLayer(isShow);
  }

  /**
   * 判断是否已加载图层
   *
   * @returns {Boolean}
   */
  hasLayer() {
    return (this._lineLayer.hasLayer()&&
    this._flowLayer.hasLayer());
  }

  /**
   * 移除图层
   */
  removeLayer() {
    this._lineLayer.removeLayer();
    this._flowLayer.removeLayer();
  }

  /**
   * 移除所有图层(销毁时调用)
   */
  removeAllLayers() {
    // 排水单元排水户连接
    this._lineLayer.removeLayer();
    this._lineLayer.removeSource();
    this._flowLayer.removeLayer();
    this._flowLayer.removeSource();
  }

  /** 私有方法 **/
  /**
   * 初始化图层
   */
  _initLayers() {
    const map = this._map;
    const minZoom = this._minzoom;

    // 排水单元排水户连接
    this._lineLayer = new DrainageUnitlineLayer({
      map: map,
      minzoom: minZoom +6.0
    });

     // 雨污混接流向
     this._flowLayer = new DrainageUnitFlowLayer({
      map: map,
      minzoom: minZoom + 6.0
    });
  }
}
