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

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

/**
 * 定义管网服务范围分析提供类
 *
 * @alias PipenetServiceRangeProvider
 *
 * @summary <用于加载管网服务范围分析图层>
 */
export default class PipenetServiceRangeProvider {
  /**
   * 构造函数
   * @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._category = 'grade'; // 排水户等级
    this.targetId = 0; // 终止点ID

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

    this._drainUnitFC = GeoJsonProvider.getEmptyFC();   // 排水单元
    this._drainEntityFC = GeoJsonProvider.getEmptyFC(); // 排水户

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

    this._drainUnitLayer = null;   // 排水单元
    this._drainEntityLayer = null; // 排水户

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

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

  /**
   * 查询管网分析数据
   * @param {String} code -厂/站编码
   * @param {String} layerType - 图层类型
   * @param {Function} callback -回调函数
   */
  async queryData(code, layerType, callback=null) {
    this.targetId = 0;

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

    const map = this._map;
    const category = layerType === 'plant' ? 'pipenet-plant' : 'pipenet-pump';
    // 获取管线网络查询url
    const queryUrl = LayerProvider.getBaseLayerQueryUrl(map, category, code);
    if (!queryUrl) {
      if (callback) { // 回调
        callback('servicerange', 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];

        this.targetId = feature.properties.target;
        if (this.targetId < 1) continue;

        // 查询上游管线流向
        await this._query('pipenet-upstream');

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

        if (this._withResult) {
          // 查询排水单元
          await this._query('pipenet-drainunit');
          // 查询排水户
          await this._query('pipenet-drainentity');
        }

        // 删除分析结果
        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) {
        // 获取唯一排水单元要素集合
        this._drainUnitFC.features = GeoJsonProvider.getUniqueFeatures(this._drainUnitFC.features, 'unit_name');
        // 设置排水单元数据
        this._drainUnitLayer.setData(this._drainUnitFC);
        // 合并排水单元
        if (this._drainUnitFC.features.length > 0) {
          resultFC.features = resultFC.features.concat(this._drainUnitFC.features);
        }

        // 获取唯一排水户要素集合
        this._drainEntityFC.features = GeoJsonProvider.getUniqueFeatures(this._drainEntityFC.features, 'drain_code');
        // 设置排水户数据
        this._drainEntityLayer.setData(this._drainEntityFC);
        // 合并排水户
        if (this._drainEntityFC.features.length > 0) {
          resultFC.features = resultFC.features.concat(this._drainEntityFC.features);
        }
      }
    } // end of if (fc && fc.features && fc.features.length > 0)

    // 更新管网总数、问题总数
    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;
    }

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

  /**
   * 停止流向
   */
  stop() {
    this._flowingLayer.stop();

    // 移除图层
    this.removeLayer();
  }

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

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

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

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

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

    // 排水户点
    if (this._drainEntityLayer) {
      this._drainEntityLayer.showLayer(isShow);
    }
    // 排水单元
    if (this._drainUnitLayer) {
      this._drainUnitLayer.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-upstream'
    });

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

    if (this._withResult) {
      // 创建排水单元图层
      this._drainUnitLayer = new SimpleFillLayer({
        map: map,
        minzoom: minZoom,
        color: '#AFEEEE',
        opacity: 0.15,
        outline: true,
        lineColor: '#AFEEEE',
        lineWidth: 2.0,
        lineOpacity: 0.75,
        //dasharray: [2.5, 1.5],
        sourceId: 'pipenet_drainunit',
      });
      // 设置空数据
      this._drainUnitLayer.setData(GeoJsonProvider.getEmptyFC());

      // 创建排水户图层
      this._drainEntityLayer = new SimpleMarkerLayer({
        map: map,
        minzoom: minZoom,
        icon: IconProvider.getDrainerIconExpression(this._category, true),
        sourceId: 'pipenet_drainentity'
      });
    }
  }

  /**
   * 查询管网分析结果
   * @param {String} type -分析类型
   */
  async _query(type) {
    const map = this._map;
    const targetId = this.targetId;

    // 获取管网函数查询url
    const queryUrl = LayerProvider.getBaseLayerQueryUrl(map, type, targetId);
    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-upstream': { // 流向
            // 合并管线数据
            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-drainunit': { // 排水单元
            fc.features.forEach((fea) => {
              fea.properties.feature_type = 'drainunit';
            });
            // 合并排水单元
            this._drainUnitFC.features = this._drainUnitFC.features.concat(fc.features);
            break;
          }
          case 'pipenet-drainentity': { // 排水户
            fc.features.forEach((fea) => {
              fea.properties.feature_type = 'drainentity';
            });
            // 合并排水户
            this._drainEntityFC.features = this._drainEntityFC.features.concat(fc.features);
            break;
          }
          default:
            break;
        }
      }
    });
  }
}
