    import { Zondy } from '../../../base'
    import { SceneServer } from '../../../service'
    import { defaultValue, Log, toJSON } from '../../../util'
    import { LayerType, LoadStatus } from '../../../base/enum'
    import { SceneLayer } from '../baseLayer'
    import Scene from './Scene'
    import IGSSceneSubLayer from './IGSSceneSubLayer'
    import { jsonClone } from '../../../util/Utils'

    /**
     * IGS的SceneLayer图层
     * @class IGSSceneLayer
     * @moduleEX LayerModule
     * @extends SceneLayer
     * @param {Object} options 构造参数
     * @param {String} [options.url] 服务基地址
     * @param {Object} [options.extendProps] 存储额外参数的属性
     */
    class IGSSceneLayer extends SceneLayer {
      constructor(options) {
        super(options)
        options = defaultValue(options, {})

        /**
         * 服务基地址
         * @member {String} IGSSceneLayer.prototype.url
         */
        this.url = defaultValue(options.url, '')
        /**
         * 图层类型
         * @member {String} IGSSceneLayer.prototype.type
         */
        this.type = LayerType.scene
        /**
         * 服务版本号
         * @member {String} IGSSceneLayer.prototype.version
         */
        this.version = undefined
        /**
         * 模型外包盒
         * @member {Object} IGSSceneLayer.prototype.boundingVolume
         */
        this.boundingVolume = undefined
        /**
         * 模型外包球
         * @readonly
         * @member {Object} IGSSceneLayer.prototype.boundingSphere
         */
        this.boundingSphere = undefined
        /**
         * 服务名
         * @member {String} IGSSceneLayer.prototype.sceneName
         */
        this.sceneName = undefined
        /**
         * 服务包含的表字段数组
         * @member {String} IGSSceneLayer.prototype.fieldInfo
         */
        this.fieldInfo = undefined
        /**
         * 模型位置
         * @member {Object} IGSSceneLayer.prototype.position
         */
        this.position = undefined
        /**
         * 模型坐标系
         * @member {Object} IGSSceneLayer.prototype.spatialReference
         */
        this.spatialReference = undefined
        /**
         * 描述信息
         * @member {String} IGSSceneLayer.prototype.description
         */
        this.description = '场景图层'
        /**
         * 场景集合
         * @member {Array<Scene>} IGSSceneLayer.prototype.scenes
         */
        this.scenes = defaultValue(options.scenes, [])

        this._sceneServer = new SceneServer({
          url: this.url
        })
      }

      load() {
        const self = this
        return this._sceneServer
          .queryServerInfo()
          .then((result) => {
            Log.info('SceneServer信息查询成功:', result)
            const data = result.data
            // igs2.0
            if (
              self.url.indexOf('/igs/rest/services/') > -1 &&
              self.url.indexOf('/SceneServer') > -1
            ) {
              const sceneOptions = JSON.parse(JSON.stringify(data))
              sceneOptions.layer = self

              self.sceneName = data.dataName
              self.documentInfo = data
              const sceneRange = data.sceneRange
              self.boundingSphere = {}
              self.boundingSphere.center = Cesium.Cartesian3.fromDegrees(
                (sceneRange.xMin + sceneRange.xMax) / 2,
                (sceneRange.yMin + sceneRange.yMax) / 2
              )
              const diff = Cesium.Cartesian3.fromDegrees(
                sceneRange.xMax - sceneRange.xMin,
                sceneRange.yMax - sceneRange.yMin
              )
              self.boundingSphere.radius = Math.abs(Math.min(diff.x, diff.y))
              return self._sceneServer.queryLayerListInfo().then((listInfoData) => {
                const layers = listInfoData.data.layers
                function setLayers(layers, _subLayers) {
                  for (let i = 0; i < layers.length; i++) {
                    if (
                      layers[i].layerType === '9' &&
                      Array.isArray(layers[i].children)
                    ) {
                      setLayers(layers[i].children, _subLayers)
                    } else {
                      layers[i].layer = self
                      _subLayers.push(new IGSSceneSubLayer(layers[i]))
                    }
                  }
                }
                const _subLayers = []
                setLayers(layers, _subLayers)
                sceneOptions.sublayers = _subLayers
                // 如果有场景，仅取第一个场景，获取其下子图层的extendOptions参数
                if (self.scenes.length >= 1) {
                  const _sceneSubLayers = self.scenes[0].sublayers
                  for (let i = 0; i < _sceneSubLayers.length; i++) {
                    for (let j = 0; j < _subLayers.length; j++) {
                      if (
                        _sceneSubLayers[i].id === _subLayers[j].id &&
                        _sceneSubLayers[i].extendOptions
                      ) {
                        _subLayers[j].extendOptions = Object.assign(
                          _subLayers[j].extendOptions,
                          _sceneSubLayers[i].extendOptions
                        )
                      }
                    }
                  }
                }
                self.scenes = [new Scene(sceneOptions)]
                self.activeScene = self.scenes[0]
                return new Promise((resolve) => {
                  self.loadStatus = LoadStatus.loaded
                  self.loaded = true
                  resolve(self)
                })
              })
            } else if (self.url.indexOf('/igs/rest/g3d/') > -1) {
              const sceneInfos = data.sceneInfos
              self.scenes = []
              for (let i = 0; i < sceneInfos.length; i++) {
                self.scenes.push(new Scene(sceneInfos[i]))
                const layers = sceneInfos[i].layers
                for (let j = 0; j < layers.length; j++) {
                  layers[j].layer = self
                  self.scenes[i].sublayers.push(new IGSSceneSubLayer(layers[j]))
                }
              }
              self.activeScene = self.scenes[0]
              self.sceneName = self.activeScene.sceneName
              self.documentInfo = data
              return new Promise((resolve) => {
                self.loadStatus = LoadStatus.loaded
                self.loaded = true
                resolve(self)
              })
            }
          })
          .catch((result) => {
            Log.info('SceneServer信息查询失败:', result)
          })
      }

      /**
       * @description 转换为json对象
       * @return {Object} json对象
       */
      toJSON() {
        const json = super.toJSON()
        json.url = this.url
        json.version = this.version
        json.boundingVolume = this.boundingVolume
        json.sceneName = this.sceneName
        json.fieldInfo = this.fieldInfo
        json.position = this.position
        json.documentInfo = this.documentInfo
        json.activeScene = toJSON(this.activeScene, Scene)
        json.boundingSphere = {
          radius: this.boundingSphere.radius,
          center: {
            x: this.boundingSphere.center.x,
            y: this.boundingSphere.center.y,
            z: this.boundingSphere.center.z
          }
        }

        const _scenes = []
        for (let i = 0; i < this.scenes.length; i++) {
          _scenes.push(toJSON(this.scenes[i], Scene))
        }
        json.scenes = _scenes

        return json
      }

      static fromJSON(json) {
        json = jsonClone(json)
        const _layer = new IGSSceneLayer(json)
        _layer._isFromJSON = true
        _layer.documentInfo = json.documentInfo
        _layer.boundingSphere = json.boundingSphere
        _layer.boundingSphere.center = new Cesium.Cartesian3(
          json.boundingSphere.center.x,
          json.boundingSphere.center.y,
          json.boundingSphere.center.z
        )
        const _scenes = []
        for (let i = 0; i < json.scenes.length; i++) {
          _scenes.push(new Scene(json.scenes[i]))
        }
        _layer.scenes = _scenes
        for (let i = 0; i < _layer.scenes.length; i++) {
          for (let j = 0; j < _layer.scenes[i].sublayers.length; j++) {
            _layer.scenes[i].sublayers[j] = new IGSSceneSubLayer(
              _layer.scenes[i].sublayers[j]
            )
          }
        }
        _layer.activeScene = _scenes[0]

        return _layer
      }

      /**
       * @description 克隆方法
       * @return {IGSSceneLayer} 图层
       */
      clone() {
        return new IGSSceneLayer(this.toJSON())
      }
    }

    Zondy.Layer.IGSSceneLayer = IGSSceneLayer
    export default IGSSceneLayer