import DataUtils from '../utils/DataUtils';
import VerifyUtils from '../utils/VerifyUtils';
import VideoLayer from '../common/VideoLayer';

import { getApi } from '../../api/http';

/**
 * 定义厂站农污绑定的视频提供类
 *
 * @alias VideoProvider
 */
 export default class VideoProvider {
  /**
   * 构造函数
   * @param {Object} options -图层选项
   */
  constructor(options) {
    /**
     * 地图对象
     * @type {Object}
     */
    this._map = options.map;

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

    // 视频图层对象
    this._videoLayer = new VideoLayer({
      map: this._map,
      minzoom: this._minzoom,
      sourceId: 'pipe_facility_video'
    });
  }

  /**
   * 设置数据
   * @param {Array|Object} data -数据
   * @param {String} gisType -设备类型字符串(,分隔)
   */
  setData(data, gisType) {
    if (!data || !gisType) return;

    const map = this._map;
    const videoLayer = this._videoLayer;

    // 查询地图服务
    let source = map.getSource(videoLayer._defaultSourceId);
    if (!source) return;

    // 字符串转sql语句字符串
    let queryStr = str2Str(gisType);

    // 构造查询语句
    let url = source._data + "&cql_filter=gis_type in (" + queryStr + ")";
    let datas = data;

    if (VerifyUtils.isObject(data)) {
      url += " and gis_code='" + data.gisCode + "'";
      datas = [data];
    }

    // 获取地图服务接口数据
    getApi(url).then((res) => {
      const fc = res.data;
      // 循环更新属性值
      for (let i = 0; i < fc.features.length; i++) {
        let feature = fc.features[i];
        let gtype = feature.properties.gis_type;
        let gcode = feature.properties.gis_code;

        // 过滤数据
        let arr = filterData(gtype, gcode);
        if (arr.length > 0) {
          feature.properties.video_id = arr[0].videoId;
        }
      }

      // 设置视频数据
      videoLayer.setData(fc);
    });

    /**
     * 字符串转SQL字符串("" => "''")
     */
    function str2Str(str) {
      let strStr = '';

      let arr = str.split(',');
      arr.forEach((item) => {
        strStr += "'" + item.toString() + "',";
      });
      if (strStr.length > 1) {
        strStr = strStr.substring(0, strStr.length - 1);
      }

      return strStr;
    }

    /**
     * 过滤数据
     */
    function filterData(gtype, gcode) {
      return datas.filter((item) => {
        return item.gisType === gtype && item.gisCode == gcode;
      });
    }
  }

  /**
   * 移除图层
   */
  removeLayer() {
    this._videoLayer.removeLayer();
    // 移除数据源
    this._videoLayer.removeSource();
  }

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

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

  /**
   * 绑定单击事件
   * @param {Function} event -事件函数
   */
  bindClickEvent(event) {
    this._videoLayer.onClick(event);
  }
}
