import DataUtils from '../utils/DataUtils';
import GeoJsonProvider from '../geog/GeoJsonProvider';
import LayerProvider from '../geog/LayerProvider';
import FlowingLayer from '../common/FlowingLayer';
import PipelineErrorLayer from '../pipeline/PipelineErrorLayer';
import PipenetFlowingLayer from './PipenetFlowingLayer';

import { pipenetMergeAnalystResult } from '../utils/PipenetUtils';
import { getApi } from '../../api/http';

/**
 * 定义管网去向分析提供类
 *
 * @alias PipenetWhereaboutsProvider
 *
 * @summary <用于加载管网去向分析图层>
 */
export default class PipenetWhereaboutsProvider {
  /**
   * 构造函数
   * @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, 10.5);

    /**
     * 是否查询管网问题
     * @type {Boolean}
     */
    this._withError = DataUtils.default(options.error, false);
    /**
     * 是否查询结果
     * @type {Boolean}
     */
    this._withResult = DataUtils.default(options.result, false);

    this.sourceId = 0; // 起始点ID

    /* 要素集 */
    this._fc = GeoJsonProvider.getEmptyFC();       // 管网流向
    this._mergedFC = GeoJsonProvider.getEmptyFC(); // 合并的管线
    this._errorFC = GeoJsonProvider.getEmptyFC();  // 管网问题

    this._plantPumpFC = GeoJsonProvider.getEmptyFC(); // 厂站

    /* 图层 */
    this._flowingLayer = null; // 管网流向
    this._errorLayer = null;   // 管网问题

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

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

  /**
   * 查询流向数据
   * @param {String} drainCode -排水户编码
   * @param {Function} callback -回调函数
   */
  async queryData(drainCode, callback=null) {
    this.sourceId = 0;

    this._fc.features = [];
    this._errorFC.features = [];
    this._plantPumpFC.features = [];
    // 结果要素集
    let resultFC = GeoJsonProvider.getEmptyFC();

    // 获取接驳井查询url
    let queryUrl = LayerProvider.getBaseLayerQueryUrl(this._map, 'drainer-connhole', drainCode);
    if (!queryUrl) {
      if (callback) { // 回调
        callback('whereabouts', resultFC);
      }
      return false;
    }

    // 查询接驳井
    const result = await getApi(queryUrl);
    const fc = result.data;
    if (fc && fc.features && fc.features.length > 0) {
      for (let i = 0; i < fc.features.length; i++) {
        const feature = fc.features[i];

        const nodeId = feature.properties.node_id;
        this.sourceId = 0;

        // 获取管线网络查询url
        queryUrl = LayerProvider.getBaseLayerQueryUrl(map, 'pipenet-down', nodeId);
        if (!queryUrl) continue;

        // 查询source
        const res = await getApi(queryUrl);
        const data = res.data;
        if (data && data.features && data.features.length > 0) {
          this.sourceId = data.features[0].properties.source;
        }
        if (this.sourceId < 1) continue;

        // 查询下游管网流向
        await this._query('pipenet-downstream');

        if (this._withError) {
          // 查询错误管网
          await this._query('pipenet-error');
        }
        if (this._withResult) {
          // 查询厂站
          await this._query('pipenet-plantpump');
        }

        // 删除分析结果
        await this._query('pipenet-delete');
      } // end of for (...)

      // 管网流向
      /*
      if (this._fc.features.length > 0) {
        // 获取唯一要素集合
        this._fc.features = GeoJsonProvider.getUniqueFeatures(this._fc.features, 'path');

        // 设置流向数据
        this._flowingLayer.setData(this._fc);
        // 开始动画
        this._flowingLayer.start();
      }
      */
      if (this._mergedFC.features.length > 0) {
        // 获取唯一要素集合
        this._mergedFC.features = GeoJsonProvider.getUniqueFeatures(this._mergedFC.features, 'path');

        // 设置流向数据
        this._flowingLayer.setData(this._mergedFC);
        // 开始动画
        this._flowingLayer.start();
      }

      if (this._withError) {
        // 管网问题
        this._errorLayer.setData(this._errorFC);

        // 合并管网问题
        if (this._errorFC.features.length > 0) {
          resultFC.features = resultFC.features.concat(this._errorFC.features);
        }
      }

      if (this._withResult) {
        // 厂站
        if (this._plantPumpFC.features.length > 0) {
          this._plantPumpFC.features = GeoJsonProvider.getUniqueFeatures(this._plantPumpFC.features, 'object_id');
          // 合并厂站
          resultFC.features = resultFC.features.concat(this._plantPumpFC.features);
        }
      }

      // 更新管网总数、问题总数
      if (resultFC.features.length > 0) {
        resultFC.features[0].properties.pipe_num = this._fc.features.length;
        let pipeLen = 0;
        this._fc.features.forEach((fea) => {
          pipeLen += fea.properties.pipe_length || 0;
        });
        resultFC.features[0].properties.pipe_len = pipeLen;

        resultFC.features[0].properties.error_num = this._errorFC.features.length;
        let errorLen = 0;
        this._errorFC.features.forEach((fea) => {
          errorLen += fea.properties.pipe_length || 0;
        });
        resultFC.features[0].properties.error_len = errorLen;
      }
    } // end of if (fc && fc.features && fc.features.length > 0)

    // 回调
    if (callback) {
      callback('whereabouts', resultFC);
    }
  }

  /**
   * 停止流向
   */
  stop() {
    this._flowingLayer.stop();
    // 移除图层
    this.removeLayer();
  }

  /**
   * 移除图层
   */
  removeLayer() {
    this._flowingLayer.removeLayer();

    // 管网问题
    if (this._errorLayer) {
      this._errorLayer.removeLayer();
    }
  }

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

    // 管网问题
    if (this._errorLayer) {
      this._errorLayer.showLayer(isShow);
    }
  }

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

    // 管网流向图层
    //this._flowingLayer = new FlowingLayer({
    this._flowingLayer = new PipenetFlowingLayer({
      map: map,
      minzoom: minZoom,
      color: this._lineColor,
      width: this._lineWidth,
      sourceId: 'pipe_flowing-downstream'
    });

    // 管网问题图层
    if (this._withError) {
      this._errorLayer = new PipelineErrorLayer({
        map: map,
        minzoom: minZoom,
      });
    }
  }

  /**
   * 查询管网分析结果
   * @param {String} type -分析类型
   */
  async _query(type) {
    if (this.sourceId < 1) return false;

    const map = this._map;
    const sourceId = this.sourceId;

    // 获取管网函数查询url
    const queryUrl = LayerProvider.getBaseLayerQueryUrl(map, type, sourceId);
    if (!queryUrl) return false;

    // 查询管网分析结果
    await getApi(queryUrl).then(res => {
      const fc = res.data;
      if (fc && fc.features && fc.features.length > 0) {
        switch (type) {
          case 'pipenet-downstream': { // 流向
            // 合并管线数据
            this._mergedFC.features = pipenetMergeAnalystResult(fc.features);

            // 合并管网流向
            this._fc.features = this._fc.features.concat(fc.features);
            break;
          }
          case 'pipenet-error': { // 错误
            fc.features.forEach((fea) => {
              fea.properties.feature_type = 'error';
            });
            // 合并管网问题
            this._errorFC.features = this._errorFC.features.concat(fc.features);
            break;
          }
          case 'pipenet-plantpump': { // 厂站
            fc.features.forEach((fea) => {
              const objectType = fea.properties.object_type;
              fea.properties.feature_type = objectType;
              fea.properties.layer_type = objectType;
              switch (objectType) {
                case 'plant': { // 厂
                  fea.properties.plant_id = fea.properties.object_id;
                  fea.properties.plant_name = fea.properties.object_name;
                  break;
                }
                case 'pump': { // 站
                  fea.properties.pump_id = fea.properties.object_id;
                  fea.properties.pump_name = fea.properties.object_name;
                  break;
                }
                default:
                  break;
              }
            });
            // 合并厂站
            this._plantPumpFC.features = this._plantPumpFC.features.concat(fc.features);
            break;
          }
          default:
            break;
        }
      }

      return true;

    }).catch(err => {
      return false;
    });
  }
}
