import DataUtils from '../utils/DataUtils';
import SimpleMarkerLayer from '../common/SimpleMarkerLayer';
import SimpleLineLayer from '../common/SimpleLineLayer';

/**
 * 定义雨污混接图层
 *
 * @alias PipenetMixingFlowLayer
 *
 * @summary <用于加载雨污混接图层>
 */
export default class PipenetMixingFlowLayer {
  /**
   * 构造函数
   * @param {Object} options -图层选项
   */
  constructor(options) {
    /**
     * 地图对象
     * @type {Object}
     */
    this._map = options.map;

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

    /**
     * 管线颜色
     * @type {String}
     */
    this._lineColor = DataUtils.default(options.color, '#2E8B57');

    /**
     * 线宽
     * @type {Number}
     */
    this._lineWidth = DataUtils.default(options.width, 3.25);

    /**
     * 是否固定(线宽)
     * @type {Boolean}
     */
    this._fixed = DataUtils.default(options.fixed, true);

    /**
     * 方向图标ID
     * @type {String}
     */
    this._directionIcon = DataUtils.default(options.directionIcon, 'faci_flow');

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

    /**
     * 图层ID
     * @type {String}
     */
    this._lineLayerId = DataUtils.default(options.layerId, this._sourceId);
    this._dashLineLayerId = this._lineLayerId + '-dash';
    this._directionLayerId = this._lineLayerId + '-direction';

    this._ratio = 200;    // 比率
    this._state = 'stop'; // 状态(play、stop)
    this._frameId = null;

    this._timer = null; // 定时器

    /** 图层 **/
    this._lineLayer = null; // 线图层
    this._dashLineLayer = null;  // 虚线图层
    this._directionLayer = null; // 方向点图层

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

  /** 公有方法 **/
  /**
   * 设置管线路径颜色
   * @param {String} color -16进制颜色字符串
   */
  setColor(color) {
    this._lineColor = color;
  }

  /**
   * 设置流向数据
   * @param {Object|Array} data -GeoJson要素/要素集/数组
   */
  setData(data) {
    // 加载图层
    if (!this.hasLayer()) {
      this.loadLayer();
    }

    // 流向线图层
    this._lineLayer.setData(data);
    this._dashLineLayer.setData(data);

    // 方向点图层
    if (this._directionLayer) {
      this._directionLayer.setData(data);
    }
  }

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

    // 流向线图层
    this._lineLayer.loadLayer();
    this._dashLineLayer.loadLayer();

    // 方向点图层
    if (this._directionLayer) {
      this._directionLayer.loadLayer();
    }
  }

  /**
   * 显示/隐藏图层
   * @param {Boolean} show -是否显示
   */
  showLayer(show = true) {
    // 流向线图层
    this._lineLayer.showLayer(show);
    this._dashLineLayer.showLayer(show);

    // 方向点图层
    if (this._directionLayer) {
      this._directionLayer.showLayer(show);
    }
  }

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

  /**
   * 移除图层
   */
  removeLayer() {
    this.stop(); // 停止动画

    // 流向线图层
    this._lineLayer.removeLayer();
    this._dashLineLayer.removeLayer();

    // 方向点图层
    if (this._directionLayer) {
      this._directionLayer.removeLayer();
    }

    // 移除数据源
    this._lineLayer.removeSource();
  }

  /**
   * 开始动画
   */
  start() {
    this._state = 'play'; // 播放
    // 显示图层
    this.showLayer(true);

    const that = this;
    // technique based on https://jsfiddle.net/2mws8y3q/
    // an array of valid line-dasharray values, specifying the lengths of the alternating dashes and gaps that form the dash pattern
    const dashArraySequence = [
      [0.0, 4, 3.0],
      [0.5, 4, 2.5],
      [1.0, 4, 2.0],
      [1.5, 4, 1.5],
      [2.0, 4, 1.0],
      [2.5, 4, 0.5],
      [3.0, 4, 0.0],
      [0, 0.5, 3, 3.5],
      [0, 1.0, 3, 3.0],
      [0, 1.5, 3, 2.5],
      [0, 2.0, 3, 2.0],
      [0, 2.5, 3, 1.5],
      [0, 3.0, 3, 1.0],
      [0, 3.5, 3, 0.5],
    ];
    /*
    const dashArraySequence = [
      [0.0, 16, 14],
      [2.0, 16, 12],
      [4.0, 16, 10],
      [6.0, 16, 8.0],
      [8.0, 16, 6.0],
      [10, 16, 4.0],
      [12, 16, 2.0],
      [14, 16, 0.0],
      [0, 2.0, 16, 16],
      [0, 4.0, 16, 14],
      [0, 6.0, 16, 12],
      [0, 8.0, 16, 10],
      [0, 10, 16, 8.0],
      [0, 12, 16, 6.0],
      [0, 14, 16, 4.0],
      [0, 16, 16, 2.0],
    ];
    */

    let step = 0;
    function _animateDashArray(timestamp) {
      if (that._state === 'play') {
        // Update line-dasharray using the next value in dashArraySequence. The
        // divisor in the expression `timestamp / 50` controls the animation speed.
        const newStep = parseInt(
          (timestamp / that._ratio) % dashArraySequence.length
        );

        if (newStep !== step) {
          that._dashLineLayer.setPaintProperty('line-dasharray', dashArraySequence[step]);
          step = newStep;
        }

        // Request the next frame of the animation.
        that._frameId = requestAnimationFrame(_animateDashArray);
      }
    }

    // start the animation
    _animateDashArray(0);
  }

  /**
   * 停止动画
   */
  stop() {
    this._state = 'stop';

    if (this._frameId) {
      cancelAnimationFrame(this._frameId);
    }
  }

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

    // 线图层
    this._lineLayer = new SimpleLineLayer({
      map: map,
      minzoom: minZoom,
      color: {
        type: 'categorical',
        property: 'category',
        stops: [
          ['1', '#13B55C'],
          ['2', '#FF4500']
        ],
        default: '#FF4500'
      },
      width: this._lineWidth,
      cap: 'butt',
      opacity: 0.35,
      fixed: this._fixed,
      //metrics: true,
      sourceId: this._sourceId,
      layerId: this._lineLayerId
    });

    // 虚线图层
    this._dashLineLayer = new SimpleLineLayer({
      map: map,
      minzoom: minZoom,
      color: {
        type: 'categorical',
        property: 'category',
        stops: [
          ['1', '#13B55C'],
          ['2', '#FF4500']
        ],
        default: '#FF4500'
      },
      width: this._lineWidth,
      cap: 'butt',
      opacity: 1.0,
      dasharray: [0, 16, 16],
      fixed: this._fixed,
      //metrics: true,
      sourceId: this._sourceId,
      layerId: this._dashLineLayerId
    });

    // 方向点图层
    if (this._directionIcon) {
      this._directionLayer = new SimpleMarkerLayer({
        map: map,
        minzoom: minZoom,
        icon: this._directionIcon,
        sourceId: this._sourceId,
        layerId: this._directionLayerId
      });
      // 设置自定义样式
      this._directionLayer.setLayoutProperty('symbol-placement', 'line');
      this._directionLayer.setLayoutProperty('symbol-spacing', [
        "interpolate",
        ["linear"],
        ["zoom"],
        10, 50,
        18, 250
      ]);
    }
  }
}
