import {BaseFeatureLayerView, Projection, SpatialReference} from '@mapgis/webclient-common'
import { CesiumInnerGraphicsLayer } from './graphic'
import ConvertRendererUtil from '../../util/ConvertRendererUtil'

const { MapGISGeojsonProvider, Style } = Cesium

class FeatureRenderView extends BaseFeatureLayerView {
  /**
   * @description 加载数据
   * @public
   * @return {FeatureSet}
   */
  _processData() {
    return new Promise((resolve) => {})
  }

  /**
   * 添加图层视图
   * @param {LayerEvent} event 图层事件
   * @return {Promise<LayerView>} 图层视图
   */
  onAdd(event) {
    const self = this
    const innerView = this.innerView
    const layer = this.layer
    const renderer = this.layer.renderer
    return this._processData().then((featureSet) => {
      return new Promise((reslove) => {
        const isDrawLabels = layer.labelsVisible
        if (isDrawLabels) {
          // ----------------解析动态注记配置（后面需要转移内核代码）-------------------------
          const geojson = featureSet.toGeoJSON()
          const isDrawLabels = layer.labelsVisible
          let labelClass = {}
          if (layer.labelingInfo && layer.labelingInfo.length > 0) {
            labelClass = layer.labelingInfo[0]
          }
          // 此处需要缓存动态视图对象
          let dynamicEntityVisualizer
          if (!FeatureRenderView.dynamicEntityVisualizer) {
            dynamicEntityVisualizer = new Cesium.DynamicEntityVisualizer(
              innerView.scene
            )
            FeatureRenderView.dynamicEntityVisualizer = dynamicEntityVisualizer
          } else {
            dynamicEntityVisualizer = FeatureRenderView.dynamicEntityVisualizer
          }

          self.innerLayer = innerView.scene.imageryLayers.addGeojsonProvider(
            new MapGISGeojsonProvider({
              _info: geojson,
              renderer: ConvertRendererUtil.rendererToFeatureRenderer(renderer),
              isDrawLabels,
              // 注记样式
              labelsOption: new Style.LabelNoteStyle(labelClass),
              // 是否开启注记避让策略
              labelDynamicEntityVisualizer:
                labelClass.deconflictionStrategy === 'none'
                  ? undefined
                  : dynamicEntityVisualizer
            })
          )
          // ------------------------------------------------------

          // 设置透明度
          self.innerLayer.translucency = layer._opacity
          // 设置可见性
          self.innerLayer.show = layer._visible
        } else {
          if (self.innerLayer) {
            self.innerLayer.destroy()
          }
          self.innerLayer = new CesiumInnerGraphicsLayer({
            id: layer.id,
            viewer: innerView,
            opacity: self.layer.opacity
          })
          // 初始化FeatureCollection
          // 如果不是WGS84相关坐标系，则进行投影变换
          if (
            featureSet.features.length > 0 &&
            !featureSet.features[0].geometry.spatialReference.isWGS84
          ) {
            for (let i = 0; i < featureSet.features.length; i++) {
              featureSet.features[i].geometry = Projection.project(
                featureSet.features[i].geometry,
                new SpatialReference({
                  wkid: 4326
                })
              )
            }
          }
          self._initFeatures(featureSet, renderer)
        }
        reslove(self)
      })
    })
  }

  /**
   * 移除图层视图
   * @param {LayerEvent} event 图层事件
   * @return {Promise<LayerView>} 图层视图
   */
  onRemove(event) {
    if (this.layer.labelsVisible) {
      this.innerView.imageryLayers.remove(this.innerLayer, true)
      // 移除注记
      if (Array.isArray(this.innerLayer._primitivesArr)) {
        this.innerLayer._primitivesArr.forEach((res) => {
          if (FeatureRenderView.dynamicEntityVisualizer && res.notePrimitive) {
            FeatureRenderView.dynamicEntityVisualizer.remove(res.notePrimitive)
          }
        })
      }
    } else {
      this.innerLayer.destroy()
    }
    this.innerLayer = null
    return Promise.resolve(this)
  }

  /**
   * 更新图层视图
   * @param {LayerViewUpdateEvent} event 图层事件
   * @return {Promise<LayerView>} 图层视图
   */
  onUpdate(event) {
    const innerLayer = this.innerLayer
    if (event.updateContent && innerLayer) {
      event.updateContent.forEach((layerUpdateContent) => {
        if (
          layerUpdateContent &&
          layerUpdateContent.operationType === 'property'
        ) {
          switch (layerUpdateContent.name) {
            case 'opacity': {
              const params = layerUpdateContent.params
              if (this.layer.labelsVisible) {
                innerLayer.translucency = layerUpdateContent.params[0]
              } else {
                innerLayer.setOpacity(params[0])
              }
              break
            }
            case 'visible': {
              const params = layerUpdateContent.params
              if (this.layer.labelsVisible) {
                innerLayer.show = layerUpdateContent.params[0]
              } else {
                innerLayer.setVisible(params[0])
              }
              break
            }
            case 'renderer': {
              if (this.layer.labelsVisible) {
                this.onRemove(event)
                this.onAdd(event)
              } else {
                this.onAdd(event)
              }
              break
            }
            default: {
              break
            }
          }
        }
        if (
          layerUpdateContent &&
          layerUpdateContent.operationType === 'method'
        ) {
          switch (layerUpdateContent.name) {
            case 'refresh': {
              if (this.layer.labelsVisible) {
                this.onRemove(event)
                this.onAdd(event)
              } else {
                this.onAdd(event)
              }
              break
            }
            default: {
              break
            }
          }
        }
      })
    }
    return Promise.resolve(this)
  }
}
export default FeatureRenderView
