import { GeometryType, Log, TextSymbol } from '@mapgis/webclient-common'
import { BaseGraphic, getPointPositions } from './index'

const { Cartesian2, LabelCollection, HorizontalOrigin } = Cesium

/**
 * 三维的几何对象
 * @private
 * @param option - {Object} 构造参数
 * @param {Feature} [option.feature = null] 构造Cesium几何的要素对象
 * */
class TextGraphic extends BaseGraphic {
  constructor(options) {
    super(options)
  }

  /**
   * 重载基类的checkSymbol方法
   * @public
   * @return {Boolean} 是否为支持的符号
   * */
  checkSymbol() {
    if (!(this._feature.symbol instanceof TextSymbol)) {
      Log.info('要素的符号类型不是TextSymbol！')
      return false
    }
    return true
  }

  /**
   * 重载基类的_createPrimitive方法
   * @private
   * */
  _createPrimitive() {
    const _geometry = this._feature.geometry
    // 构造cesium的billboard的Primitive对象
    if (!this._primitiveCollection) {
      this._primitiveCollection = new LabelCollection()
    }
    switch (_geometry.type) {
      case GeometryType.point:
      case GeometryType.polygon:
      case GeometryType.extent:
      case GeometryType.circle:
        const _label = this._labelsCollection.add(
          this._createLabelOptions(this._getPositions()[0])
        )
        _label.id = this._feature.id
        this._labels.push(_label)
        break
      case GeometryType.multiPoint:
      case GeometryType.multiPolygon:
        const _positions = this._getPositions()
        for (let i = 0; i < _positions.length; i++) {
          const _label = this._labelsCollection.add(
            this._createLabelOptions(_positions[i])
          )
          _label.id = this._feature.id
          this._labels.push(_label)
        }
        break
      default:
        break
    }
  }

  /**
   * 重载基类的_getPositions方法
   * @private
   * @return {Array<Cartesian3>} Cesium的点坐标数组
   * */
  _getPositions() {
    return getPointPositions(this._feature)
  }

  /**
   * 通过点坐标构造一个label的初始化参数
   * @private
   * @param {Cartesian3} position 三维几何点坐标
   * @return {Object} label构造参数
   * */
  _createLabelOptions(position) {
    // 获取symbol对象
    const _symbol = this._feature.symbol
    // 构造文字颜色
    const _color = this._getCesiumColor(_symbol.color)
    // 设置图层透明度
    _color.alpha *= this._layerOpacity
    return {
      // 几何坐标
      position,
      // 文字内容
      text: _symbol.text,
      // 文字斜体、文字宽度、字体大小、字体名等
      font: `${_symbol.font.style} ${_symbol.font.weight}  ${_symbol.font.size}px  ${_symbol.font.family}`,
      // 文字颜色
      fillColor: _color,
      // 文字像素偏移
      pixelOffset: new Cartesian2(_symbol.xoffset, _symbol.yoffset * -1),
      // 文字水平排放位置
      horizontalOrigin: HorizontalOrigin.CENTER
    }
  }
}

export default TextGraphic
