import { getBaseUrl } from '@mapgis/webclient-common'
import FeatureRenderView from './support/FeatureRenderView'
import { getTilingSchemeBySpatialReference } from '../view/utils/support/utils'

class IGSFeatureLayerView extends FeatureRenderView {
  _processData() {
    const layer = this.layer
    // (默认查询100000条要素)
    const queryCount = 100000
    const query = layer._createQueryOption()
    query.resultRecordCount = queryCount
    return layer.queryFeatures(query).then((res) => {
      return res
    })
  }

  /**
   * 添加图层视图
   * @param {LayerEvent} event 图层事件
   * @return {Promise<LayerView>} 图层视图
   */
  onAdd(event) {
    const self = this
    const layer = this.layer
    const innerView = this.innerView

    // 设置渲染模式
    if (layer.renderMode === 'server') {
      // 获取瓦片切分方式
      let tilingScheme
      if (layer.spatialReference) {
        tilingScheme = getTilingSchemeBySpatialReference(
          layer.spatialReference,
          layer.extent
        )
      } else {
        tilingScheme = new Cesium.GeographicTilingScheme({
          rectangle: Cesium.Rectangle.fromDegrees(-180.0, -90.0, 180.0, 90.0),
          ellipsoid: Cesium.Ellipsoid.WGS84,
          numberOfLevelZeroTilesX: 2,
          numberOfLevelZeroTilesY: 1
        })
      }

      const resourceUrl = layer.url
      const httpString = getBaseUrl(resourceUrl)
      let options
      if (layer._igsVersion === '1.0') {
        options = {
          // 服务基地址
          url: `${httpString}/igs/rest/mrms/layers`,
          // gdbps地址数组
          gdbps: [layer.gdbp],
          tilingScheme,
          filters: layer.definitionExpression
            ? `0:${layer.definitionExpression}`
            : ''
        }
      } else {
        options = {
          // 服务基地址 http://localhost:8089/igs/rest/services/system/ResourceServer/tempData/image
          url: `${httpString}/igs/rest/services/system/ResourceServer/tempData`,
          // gdbps地址数组
          gdbps: [layer.gdbp],
          tilingScheme,
          filters: layer.definitionExpression
            ? `0:${layer.definitionExpression}`
            : ''
        }
      }

      // 加载IGS二维矢量图层服务
      this.innerLayer = innerView.imageryLayers.addImageryProvider(
        new Cesium.MapGISMapServerImageryProvider(options)
      )

      return Promise.resolve(self)
    } else {
      return super.onAdd(event)
    }
  }

  /**
   * 移除图层视图
   * @param {LayerEvent} 图层事件
   * @return {Promise<LayerView>} 图层视图
   */
  onRemove(event) {
    const self = this
    const layer = this.layer
    if (layer.gdbp) {
      this.innerView.imageryLayers.remove(this.innerLayer)
      return Promise.resolve(self)
    }
    return super.onRemove(event)
  }
}

export default IGSFeatureLayerView
