import DataUtils from '../utils/DataUtils';
import CommonUtils from '../utils/CommonUtils';
import VerifyUtils from '../utils/VerifyUtils';
import IconProvider from '../geog/IconProvider';
import LayerProvider from '../geog/LayerProvider';
import GeoJsonProvider from '../geog/GeoJsonProvider';
import SimpleMarkerLayer from '../common/SimpleMarkerLayer';
import ClusterLayer from '../common/ClusterLayer';
import ConnholeLayer from '../pipeline/ConnholeLayer';
import PipenetInProvider from '../pipeline/PipenetInProvider';
import DrainUnitLayer from './DrainUnitLayer';

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

/**
 * 定义排水户分析提供类
 *
 * @alias DrainEntityAnalystProvider
 *
 * @summary <用于排水户分析地图交互>
 */
export default class DrainEntityAnalystProvider {
  /**
   * 构造函数
   * @param {Object} options -排水户选项
   */
  constructor(options) {
    /**
     * 地图对象
     * @type {Object}
     */
    this._map = options.map;

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

    /**
     * 聚合最大缩放层级
     * @type {Number}
     */
    this._clusterMaxZoom = DataUtils.default(options.clusterMaxZoom, 14);

    /**
     * 聚合半径
     * @type {Number}
     */
    this._clusterRadius = DataUtils.default(options.clusterRadius, 120);

    this._category = 'grade'; // 排水户等级
    this._focusIcon = 'busi_focus'; // 聚焦图标

    this._drainEntityFeature = null; // 选中的排水户要素
    this._connholeFeature = null;    // 选中的接驳井要素

    // 排水户点
    this._defaultSourceId = 'pipe_drainage_entity';
    this._sourceId = 'pipe_drainers';  // pipe_drainer
    this._clusterSourceId = this._sourceId + '_cluster';
    this._unitSourceId = this._sourceId + '_unit';
    this._pointSourceId = this._sourceId + '_entity';

    /** 图层对象 **/
    // 点聚合图层
    this._clusterLayer = new ClusterLayer({
      map: this._map,
      minzoom: this._minzoom,
      icon: 'drain_all',
      clusterMaxzoom: this._clusterMaxZoom,
      clusterRadius: this._clusterRadius,
      //defaultSourceId: this._defaultSourceId,
      sourceId: this._clusterSourceId
    });

    this._focusLayer = null; // 聚焦

    this._drainUnitLayer = null;   // 排水单元
    this._drainEntityLayer = null; // 排水户点
    this._pipenetInProvider = null; // 排水单元内管网
    this._connholeLayer = null;     // 接驳井
  }

  /** 静态方法 **/
  /**
   * 根据街镇获取查询参数
   * @param {Object} town -街镇对象
   * @param {Object} params -页面参数
   */
  static getQueryParamsByTown(town, params) {
    let queryParams = {};

    // 镇街
    queryParams.drainersRegion = null;
    if (town) {
      queryParams.drainersRegion = town.id.toString();
    }

    // 排水户类型
    queryParams.drainersStype = null;
    if (params.catalog && params.catalog.length > 0) {
      queryParams.drainersStype = CommonUtils.ids2String(params.catalog);
    }

    // 许可证状态
    queryParams.licenseStatusList = null;
    if (params.status && params.status.length > 0) {
      queryParams.licenseStatusList = CommonUtils.ids2String(params.status);
    }

    // 社区
    queryParams.sewagePlantId = null;
    if (params.plant && params.plant.length > 0) {
      queryParams.sewagePlantId = CommonUtils.ids2String(params.plant);
    }

    //排水单元
    queryParams.drainersUnit = null;
    if (params.unit && params.unit.length > 0) {
      queryParams.drainersUnit = CommonUtils.ids2String(params.unit);
    }

    //排水户状态
    queryParams.drainersState = null;
    if (params.dStatus && params.dStatus.length > 0) {
      queryParams.drainersState = CommonUtils.ids2String(params.dStatus);
    }

    //排水户类别
    queryParams.drainersCategory = null;
    if (params.category && params.category.length > 0) {
      queryParams.drainersCategory = CommonUtils.ids2String(params.category);
    }

    return queryParams;
  }

  /** 公有方法 **/
  /**
   * 设置数据
   * @param {Object|Array|String} data -GeoJson要素集/条件语句
   *
   * @summary <当data参数为String类型时，可以为空，或者是查询语句，例如：town='8'>
   */
  setClusterData(data) {
    // 隐藏红线图层
    if (this._drainUnitLayer) {
      this._drainUnitLayer.showLayer(false);
    }

    this._drainEntityFeature = null;
    this._connholeFeature = null;

    // 判断是否图层字段
    let isLayerField = (!data) || VerifyUtils.isString(data);
    // 获取图标表达式
    let iconExpression = IconProvider.getDrainerIconExpression(this._category, isLayerField);

    // 设置图标
    this._clusterLayer.setIcon(iconExpression);

    // 加载图层
    if (!this._clusterLayer.hasLayer()) {
      this._clusterLayer.loadLayer();
    }
    // 隐藏图层
    this._clusterLayer.showLayer(false);

    if (isLayerField) { // 条件语句
      const map = this._map;
      let source = map.getSource(this._defaultSourceId);
      if (source) {
        let url = source._data + '&cql_filter=' + data;
        // 设置图层查询语句
        this._clusterLayer.setData(url);
      }
    } else { // 数据
      this._clusterLayer.setData(data);
    }
  }

  /**
   * 添加数据
   * @param {Object} data -GeoJson要素集
   */
  appendClusterData(data) {
    if (!data ||
        !VerifyUtils.isGeoJsonFC(data) ||
        !data.features || data.features.length === 0) {
      return;
    }

    this._clusterLayer.appendData(data);
  }

  /**
   * 设置排水户数据
   * @param {Object} data -GeoJSON要素
   */
  setDrainEntity(data) {
    if (!data && !VerifyUtils.isGeoJsonFeature(data)) return;

    const drainCode = data.properties.drain_code;
    if (this._drainEntityFeature &&
        this._drainEntityFeature.properties.drain_code === drainCode) {
      return;
    }

    const unitCode = data.properties.unit_code; // 排水单元

    this._drainEntityFeature = data;
    this._connholeFeature = null;

    // 查询排水单元数据
    this._queryDrainUnit(drainCode);
    // 查询排水单元内管网数据
    //this._queryPipenetIn(unitCode);
    // 查询接驳井数据
    this._queryConnhole(drainCode);

    // 设置排水户数据
    if (!this._drainEntityLayer) {
      // 获取图标表达式
      let iconExpression = IconProvider.getDrainerIconExpression(this._category, true);

      this._drainEntityLayer = new SimpleMarkerLayer({
        map: this._map,
        minzoom: this._minzoom,
        icon: iconExpression,
        field: 'drain_name',
        sourceId: this._pointSourceId
      });
    }
    this._drainEntityLayer.setData(data);

    // 更新聚焦数据
    this._updateFocusData();
  }

  /**
   * 设置接驳井数据
   * @param {Object} data -GeoJSON要素
   */
  setConnhole(data) {
    if (!data && !VerifyUtils.isGeoJsonFeature(data)) return;

    let nodeId = data.properties.node_id;
    if (this._connholeFeature &&
      this._connholeFeature.properties.node_id === nodeId) {
      return;
    }
    this._connholeFeature = data;

    // 查询排水户数据
    this._queryDrainEntity(nodeId);

    // 更新聚焦数据
    this._updateFocusData();
  }

  /**
   * 显示/隐藏聚焦图层
   * @param {Boolean} show -是否显示
   */
  showClusterLayer(show) {
    this._clusterLayer.showLayer(show);
  }

  /**
   * 移除相关的图层
   */
  removeRelatedLayers() {
    // 聚焦
    if (this._focusLayer) {
      this._focusLayer.removeLayer();
      this._focusLayer.removeSource();
    }

    // 排水单元
    if (this._drainUnitLayer) {
      this._drainUnitLayer.removeLayer();
    }
    // 排水户
    if (this._drainEntityLayer) {
      this._drainEntityLayer.removeLayer();
      this._drainEntityLayer.removeSource();
    }

    // 排水单元内管网
    if (this._pipenetInProvider) {
      this._pipenetInProvider.removeAllLayers();
    }
    // 接驳井
    if (this._connholeLayer) {
      this._connholeLayer.removeLayer();
    }
  }

  /**
   * 移除所有图层
   */
  removeAllLayers() {
    // 点聚合图层
    this._clusterLayer.removeLayer();
    this._clusterLayer.removeSource();

    // 聚焦
    if (this._focusLayer) {
      this._focusLayer.removeLayer();
      this._focusLayer.removeSource();
    }

    // 排水单元
    if (this._drainUnitLayer) {
      this._drainUnitLayer.removeLayer();
    }
    // 排水户
    if (this._drainEntityLayer) {
      this._drainEntityLayer.removeLayer();
      this._drainEntityLayer.removeSource();
    }

    // 排水单元内管网
    if (this._pipenetInProvider) {
      this._pipenetInProvider.removeAllLayers();
    }
    // 接驳井
    if (this._connholeLayer) {
      this._connholeLayer.removeLayer();
    }
  }

  /**
   * 绑定单击事件
   * @param {String} name -事件名称
   * @param {Function} event -事件函数
   */
  onEvent(name, event) {
    this._clusterLayer.onEvent(name, event);
  }

  /**
   * 绑定排水户事件
   * @param {String} name -事件名称
   * @param {Function} event -事件函数
   */
  onDrainEnityEvent(name, event) {
    this._drainEntityLayer.onEvent(name, event);
  }

  /**
   * 绑定接驳井单击事件
   * @param {Function} event -事件函数
   */
  onConnholeClick(event) {
    this._connholeLayer.onClick(event);
  }

  /** 私有方法 **/
  /**
   * 查询排水单元数据
   * @param {String} drainCode -排水户编码
   */
  _queryDrainUnit(drainCode) {
    const map = this._map;

    // 排水单元图层
    if (!this._drainUnitLayer) {
      this._drainUnitLayer = new DrainUnitLayer({
        map: map,
        minzoom: this._minzoom,
        opacity: 0.25,
        sourceId: this._unitSourceId
      });
    }
    // 设置空数据
    let fc = GeoJsonProvider.getEmptyFC();
    this._drainUnitLayer.setData(fc);

    // 获取排水单元查询url
    let queryUrl = LayerProvider.getBaseLayerQueryUrl(map, 'drainer-drainunit', drainCode);
    if (!queryUrl) return;

    // 获取地图服务接口数据
    getApi(queryUrl).then((res) => {
      fc = res.data;
      if (fc && fc.features && fc.features.length > 0) {
        // 设置数据
        this._drainUnitLayer.setData(fc);
      }
    }).catch((err) => {
      console.log(err);
    });
  }

  /**
   * 查询排水单元内管网数据
   * @param {String} unitCode -排水单元编码
   */
  _queryPipenetIn(unitCode) {
    const map = this._map;

    if (!this._pipenetInProvider) {
      this._pipenetInProvider = new PipenetInProvider({
        map: map,
        pipelineSourceId: 'pipenet_pipeline_in',
        manholeSourceId: 'pipenet_manhole_in'
      });
    }
    const provider = this._pipenetInProvider;

    // 设置空数据
    provider.setData('pipelinein', GeoJsonProvider.getEmptyFC());
    provider.setData('manholein', GeoJsonProvider.getEmptyFC());

    // 查询排水单元内管线数据
    const pipelineUrl = LayerProvider.getBaseLayerQueryUrl(map, 'pipeline-in', unitCode);
    if (pipelineUrl) {
      getApi(pipelineUrl).then(res => {
        const fc = res.data;
        // 设置雨水管线数据
        setPipenetInData('pipelinein', '1', fc);
        // 设置污水管线数据
        setPipenetInData('pipelinein', '2', fc);
      });
    }

    // 查询排水单元内检查井数据
    const manholeUrl = LayerProvider.getBaseLayerQueryUrl(map, 'manhole-in', unitCode);
    if (manholeUrl) {
      getApi(manholeUrl).then(res => {
        const fc = res.data;
        // 设置雨水检查井数据
        setPipenetInData('manholein', '1', fc);
        // 设置污水检查井数据
        setPipenetInData('manholein', '2', fc);
      });
    }

    /**
     * 设置排水单元内管网数据
     * @param {String} layerType -图层类型
     * @param {String} category -类别
     * @param {Object} fc -要素集
     */
    function setPipenetInData(layerType, category, fc) {
      const newFC = GeoJsonProvider.getEmptyFC();
      // 过滤数据
      newFC.features = fc.features.filter(feature => {
        return feature.properties.category === category;
      });

      category = category === '1' ? 'rain' : 'sewage';
      const type = layerType + category;
      provider.setData(type, newFC);
    }
  }

  /**
   * 查询排水户数据
   * @param {String} nodeId -接驳井编码
   */
  _queryDrainEntity(nodeId) {
    // 获取排水户查询url
    let queryUrl = LayerProvider.getBaseLayerQueryUrl(map, 'drainer-drainentity', nodeId);
    if (!queryUrl) return;

    // 获取地图服务接口数据
    getApi(queryUrl).then((res) => {
      let fc = res.data;
      if (fc && fc.features && fc.features.length > 0) {
        // 设置数据
        this._drainEntityLayer.setData(fc);
      }
    }).catch((err) => {
      console.log(err);
    });
  }

  /**
   * 查询接驳井数据
   * @param {String} drainCode -排水户编码
   */
  _queryConnhole(drainCode) {
    const map = this._map;

    if (!this._connholeLayer) {
      this._connholeLayer = new ConnholeLayer({
        map: map,
        minzoom: this._minzoom,
        icon: 'manhole_conn',
        size: 0.75,
        field: 'node_name',
        sourceId: 'pipe_connect_manhole'
      });
    }
    // 设置空数据
    let fc = GeoJsonProvider.getEmptyFC();
    this._connholeLayer.setData(fc);

    // 获取接驳井查询url
    let queryUrl = LayerProvider.getBaseLayerQueryUrl(map, 'drainer-connhole', drainCode);
    if (!queryUrl) return;

    let drainName = this._drainEntityFeature ? this._drainEntityFeature.properties.drain_name : '';
    // 获取地图服务接口数据
    getApi(queryUrl).then((res) => {
      fc = res.data;
      if (fc && fc.features && fc.features.length > 0) {
        // 更新属性
        for (let i = 0; i < fc.features.length; i++) {
          let feature = fc.features[i];
          feature.properties.node_name = drainName + '-' + (i + 1) + '号井';
        }
        // 设置数据
        this._connholeLayer.setData(fc);
      }
    }).catch((err) => {
      console.log(err);
    });
  }

  /**
   * 更新聚焦数据
   */
  _updateFocusData() {
    const map = this._map;

    const fc = GeoJsonProvider.getEmptyFC();
    if (this._drainEntityFeature) {
      fc.features.push(this._drainEntityFeature);
    }
    if (this._connholeFeature) {
      fc.features.push(this._connholeFeature);
    }

    // 聚焦图层
    if (!this._focusLayer) {
      this._focusLayer = new SimpleMarkerLayer({
        map: map,
        minzoom: this._minzoom,
        icon: this._focusIcon,
        sourceId: 'pi_drain_focus'
      });
    }
    // 设置聚焦数据
    this._focusLayer.setData(fc);
  }
}
