<template>
  <el-tabs v-model="activeName" @tab-click="tabClick">
    <el-tab-pane label="基础图层" name="baselayer">
      <el-tree
        ref="baseTree"
        empty-text=""
        @check="checkLayer"
        :data="baselayers"
        node-key="id"
        :props="defaultProps"
        show-checkbox
        :default-expanded-keys="baseDefaultExpand"
        :default-checked-keys="baseDefaultCheck"
      >
      </el-tree>
    </el-tab-pane>
    <el-tab-pane label="专题图" name="themelayer">
      <el-tree
        ref="themeTree"
        empty-text=""
        @check="checkLayer"
        :data="themelayers"
        node-key="id"
        :props="defaultProps"
        show-checkbox
        :default-expanded-keys="themeDefaultExpand"
        :default-checked-keys="themeDefaultCheck"
      >
      </el-tree>
    </el-tab-pane>
    <el-tab-pane label="设计管线" name="sjpipelayer">
      <el-tree
        ref="sjTree"
        empty-text=""
        @check="checkLayer"
        :data="sjlayers"
        node-key="id"
        :props="defaultProps"
        show-checkbox
        :default-expanded-keys="sjDefaultExpand"
        :default-checked-keys="sjDefaultCheck"
      >
      </el-tree>
    </el-tab-pane>
    <el-tab-pane label="普查管线" name="pcpipelayer">
      <el-tree
        ref="pcTree"
        empty-text=""
        @check-change="checkLayer"
        :data="pclayers"
        node-key="id"
        :props="defaultProps"
        show-checkbox
        :default-expanded-keys="pcDefaultExpand"
        :default-checked-keys="pcDefaultCheck"
      >
      </el-tree>
    </el-tab-pane>
  </el-tabs>
</template>
<script>
import Config from './config.json'
import $ from 'jquery'
const LayerType = {
  S3M: 'S3M',
  Imagery: 'Imagery',
  Terrain: 'Terrain',
  Mvt: 'Mvt'
}
export default {
  name: 'LayerList',
  data() {
    return {
      activeName: 'baselayer',
      defaultProps: {
        label: 'label',
        children: 'children'
      },
      currentLayer: 'sjpipelayer',
      currentRef: '',
      layer: {
        pclayer: 'pcpipelayer',
        yllayer: 'ylpipelayer',
        jglayer: 'jgpipelayer',
        baselayer: 'baselayer',
        sjlayer: 'sjpipelayer',
        themelayer: 'themelayer'
      },

      baselayers: [],
      themelayers: [],
      sjlayers: [],
      pclayers: [],
      baseDefaultExpand: ['baselayer_0'],
      baseDefaultCheck: [],
      themeDefaultExpand: ['themelayer_0'],
      themeDefaultCheck: [],
      sjDefaultExpand: ['sjpipelayer_0'],
      sjDefaultCheck: [],
      pcDefaultExpand: ['pcpipelayer_0'],
      pcDefaultCheck: []
    }
  },
  computed: {
    AppX() {
      return this.$store.getters.AppX
    }
  },
  mounted() {
    this.currentRef = this.$refs.baseTree
    if (window.viewer) {
      this.viewer = window.viewer
      this.initMapConfig()
      this.initLayers()
    } else {
      console.error('viewer未初始化')
    }
  },
  methods: {
    tabClick(data) {
      switch (data.name) {
        case this.layer.pclayer:
          this.currentRef = this.$refs.pcTree
          break
        case this.layer.baselayer:
          this.currentRef = this.$refs.baseTree
          break
        case this.layer.sjlayer:
          this.currentRef = this.$refs.sjTree
          break
        case this.layer.themelayer:
          this.currentRef = this.$refs.themeTree
          break
      }
    },
    /**
     *该方法用于生成图层管理配置
     */
    initMapConfig() {
      const themeLayer = []
      const baseLayer = []
      const gisSource = this.AppX.appConfig.gisResource
      const themeConfig = gisSource[Config.themeMap].config
      const themegroup = this.initThemelayers(themeConfig)
      // for (let i = 0; i < themeConfig.length; i++) {
      //     const themeitem = themeConfig[i];
      //     themeLayer.push({ label: themeitem.name, name: themeitem.key, type: "img", add: true, dic: Config.themeMap, sort: themeitem.sort ? themeitem.sort : 1000 });
      // }
      // //排序
      // themeLayer.sort((a, b) => { return a.sort - b.sort; })
      Config.themelayer[0].data = themegroup
      const mapService = Config.mapService
      for (let j = 0; j < mapService.length; j++) {
        const keyName = mapService[j]
        const config = gisSource[mapService[j]].config
        for (let k = 0; k < config.length; k++) {
          const item = config[k]
          baseLayer.push({
            label: item.name,
            name: item.key,
            type: 'img',
            add: true,
            dic: keyName,
            sort: item.sort ? item.sort : 1000
          })
        }
      }
      //排序
      baseLayer.sort((a, b) => {
        return a.sort - b.sort
      })
      Config.baselayer[0].data = Config.baselayer[0].data.concat(baseLayer)
    },
    /**
     * 该方法用于专题图分组组合
     */
    initThemelayers(themeConfig) {
      const group = []
      for (let layerkey in themeConfig) {
        const themeitem = themeConfig[layerkey]
        const groupLayer = _.find(group, (item) => {
          return item.label === themeitem.sourceGroup
        })
        if (!groupLayer && themeitem.sourceGroup) {
          //新建分组
          group.push({
            label: themeitem.sourceGroup,
            data: [
              {
                label: themeitem.name,
                name: layerkey,
                type: 'img',
                add: true,
                dic: Config.themeMap,
                sort: themeitem.sort ? themeitem.sort : 1000
              }
            ],
            sort: 1000
          })
        } else if (groupLayer && themeitem.sourceGroup) {
          //现有分组增加
          groupLayer.data.push({
            label: themeitem.name,
            name: layerkey,
            type: 'img',
            add: true,
            dic: Config.themeMap,
            sort: themeitem.sort ? themeitem.sort : 1000
          })
        } else if (!themeitem.sourceGroup) {
          //现有分组增加
          group.push({
            label: themeitem.name,
            name: layerkey,
            type: 'img',
            add: true,
            dic: Config.themeMap,
            sort: themeitem.sort ? themeitem.sort : 1000
          })
        }
      }
      //组内分组排序
      group.forEach((item) => {
        if (item.data) {
          item.data.sort((a, b) => {
            return a.sort - b.sort
          })
          item.sort = item.data[0].sort
        }
      })
      //分组排序
      group.sort((a, b) => {
        return a.sort - b.sort
      })
      return group
    },
    /**
     * 加载图层列表
     */
    initLayers() {
      //树状数据处理
      this.loadLayerList()
    },
    /**
     * 加载图层信息
     */
    loadLayerList() {
      let initlayer = null
      for (let layertype in this.layer) {
        switch (this.layer[layertype]) {
          case this.layer.pclayer:
            initlayer = Config.pcpipelayer
            break
          case this.layer.baselayer:
            initlayer = Config.baselayer
            break
          case this.layer.sjlayer:
            initlayer = Config.sjpipelayer
            break
          case this.layer.themelayer:
            initlayer = Config.themelayer
            break
        }
        this.currentLayer = this.layer[layertype]
        let layerConfig = []
        this.getNode(initlayer, this.layer[layertype], layerConfig)
        switch (this.layer[layertype]) {
          case this.layer.pclayer:
            this.pclayers = layerConfig
            break
          case this.layer.baselayer:
            this.baselayers = layerConfig
            break
          case this.layer.sjlayer:
            this.sjlayers = layerConfig
            break
          case this.layer.themelayer:
            this.themelayers = layerConfig
            break
        }
      }
    },
    /**
     * 处理图层配置
     *
     * */
    getNode(data, pid, parentLayer) {
      let num = 0
      let checkednum = 0
      let isExitNum = 0
      data.forEach((item, i) => {
        if (item.data) {
          let parentConfig = { label: item.label, children: [], id: pid + '_' + num }
          let checked = this.getNode(item.data, pid + '_' + num, parentConfig.children)
          if (checked && checked != 'NoExit') {
            checkednum++
          }
          if (checked && checked == 'NoExit') {
            isExitNum++
          }
          let open = false
          if (pid.split('_').length == 1) {
            open = true
          }
          if (checked != 'NoExit') {
            parentLayer.push(parentConfig)
          }
        } else {
          let checked = false
          let type = null
          let Exit = false
          //判断是否属于layers图层
          if (item.name) {
            let data_item = item.name.split(',')
            if (data_item.length > 0) {
              $.each(
                data_item,
                function (i, item2) {
                  let item_search1 = this.viewer.scene.layers.find(item2)
                  if (item_search1) {
                    type = LayerType.S3M
                    checked = item_search1.visible
                    Exit = true
                  }
                }.bind(this)
              )
            }
          }
          //判断是否属于影像图层
          if (type == null) {
            //添加影像，不勾选
            if (item.type === 'img' && item.add) {
              checked = !item.add
              type = LayerType.Imagery
              Exit = true
            }

            $.each(this.viewer.imageryLayers._layers, function (index, item_s) {
              if (item_s.imageryProvider.credit && item.name == item_s.imageryProvider.credit.html) {
                checked = item_s.show
                type = LayerType.Imagery
                Exit = true
              }
            })
          }
          //判断是否属于地形图层
          if (type == null && item.label == '地形') {
            if (this.viewer.terrainProvider._credit) {
              if (
                this.AppX.runtimeConfig.terrain === this.viewer.terrainProvider &&
                this.viewer.terrainProvider._credit.html == item.label
              ) {
                checked = true
                Exit = true
              } else {
                checked = false
              }
            } else {
              checked = false
            }
            type = LayerType.Terrain
          }
          //判断是否属于切片图层
          if (type == null && item.type == 'mvt') {
            //添加影像，不勾选
            if (item.add) {
              checked = !item.add
              type = LayerType.Mvt
              Exit = true
            }
            let layer = this.viewer.scene.getVectorTilesLayer(item.name)
            if (layer) {
              if (layer.show) {
                checked = true
                Exit = true
              } else {
                checked = false
              }
            } else {
              checked = false
            }
          }
          if (checked) {
            checkednum++
            //设置树组件默认选中节点
            switch (this.currentLayer) {
              case this.layer.pclayer:
                this.pcDefaultCheck.push(pid + '_' + num)
                break
              case this.layer.baselayer:
                this.baseDefaultCheck.push(pid + '_' + num)
                break
              case this.layer.sjlayer:
                this.sjDefaultCheck.push(pid + '_' + num)
                break
              case this.layer.themelayer:
                this.themeDefaultCheck.push(pid + '_' + num)
                break
            }
          }
          if (Exit) {
            parentLayer.push({
              id: pid + '_' + num,
              dic: item.dic,
              label: item.label,
              layer_name: item.name,
              type: type,
              name_2d: item.name_2d ? item.name_2d : ''
            })
          } else {
            isExitNum++
          }
        }
        num++
      })
      if (isExitNum == data.length) {
        return 'NoExit'
      }
      if (checkednum == data.length - isExitNum) {
        return true
      }
    },
    /**
     * 图层勾选控制
     * @param data node对象
     * @param checked 选中状态
     */
    checkLayer(data, checkedkeys) {
      const checkednodes = this.currentRef.getCheckedKeys()
      const checked = !(checkednodes.indexOf(data.id) === -1)
      this.onAndClose(data, checked)
    },
    /**
     * 图层的关闭和打开
     *
     */
    onAndClose(clickNode, checked) {
      let layer = undefined
      const that = this
      if (!clickNode) {
        return
      }
      if (clickNode.children) {
        $.each(
          clickNode.children,
          function (i, item) {
            this.onAndClose(item, checked)
          }.bind(this)
        )
      } else {
        let data = null
        if (clickNode.name_2d != '') {
          $.each(this.maplayer, function (i, item) {
            let names = clickNode.name_2d.split(',')
            if (names.length > 1) {
              $.each(names, function (i2, item2) {
                if (item.name == item2) {
                  item.visible = checked
                }
              })
            } else {
              if (item.name == clickNode.name_2d) {
                item.visible = checked
              }
            }
          })
        }
        switch (clickNode.type) {
          case LayerType.S3M:
            data = clickNode.layer_name.split(',')
            if (data.length > 0) {
              $.each(
                data,
                function (i, item) {
                  layer = this.viewer.scene.layers.find(item)
                  if (layer) {
                    layer.visible = checked
                  }
                }.bind(this)
              )
            }
            break
          case LayerType.Imagery:
            const imageLayers = this.viewer.imageryLayers
            data = clickNode.layer_name.split(',')
            if (data.length > 0) {
              $.each(data, function (i, item) {
                that.imageLayerControl(item, clickNode.dic, checked)
              })
            }
            break
          case LayerType.Terrain:
            if (checked) {
              this.viewer.terrainProvider = this.AppX.runtimeConfig.terrain
            } else {
              this.viewer.scene.terrainProvider = new Cesium.EllipsoidTerrainProvider() //无法控制地形显隐，替换一个简单地形
            }
            break
          case LayerType.Mvt:
            data = clickNode.layer_name.split(',')
            if (data.length > 0) {
              $.each(data, function (i, item) {
                that.mvtLayerControl(item, checked)
              })
            }
            break
        }
      }
    },
    /**
     * 该方法用于增加
     * @param key 影像服务key,同时也是credit
     * @param dic 影像服务字典编码
     * @param checked 是否打开
     */
    imageLayerControl(key, dic, checked) {
      if (checked) {
        const gisitem = this.AppX.appConfig.gisResource[dic].config[key]
        if (gisitem) {
          const url = gisitem.url
          this.viewer.imageryLayers.addImageryProvider(
            new Cesium.SuperMapImageryProvider({
              url: url,
              credit: key
            })
          )
        }
      } else {
        const imageLayers = this.viewer.imageryLayers
        for (let i = 0; i < imageLayers.length; i++) {
          const img = imageLayers.get(i)
          if (img.imageryProvider.credit && img.imageryProvider.credit.html === key) {
            imageLayers.remove(img, true)
          }
        }
      }
    },
    /**
     * 切片图层得打开关闭
     * @param key 服务key,同时也是credit
     * @param checked 是否打开
     */
    mvtLayerControl(key, checked) {
      if (checked) {
        const url = this.AppX.appConfig.gisResource['img'].config[key].url
        this.AppX.runtimeConfig.viewer.scene.addVectorTilesMap({
          url: url,
          name: key
        })
      } else {
        this.AppX.runtimeConfig.viewer.scene.removeVectorTilesMap(key)
      }
    },
    /**
     * 缩放到图层
     */
    zoomToLayer(event, treeId, clickNode) {
      let searchNode = null
      if (!clickNode) {
        return
      }
      if (clickNode.type == undefined || clickNode.type == null) {
        return
      }
      const layerType = clickNode.type
      switch (layerType) {
        case LayerType.S3M:
          const id = clickNode.layer_name
          const clickLayer = _.find(this.viewer.scene.layers.layerQueue, (layer) => {
            return layer.name === clickNode.layer_name.split(',')[0]
          })
          this.viewer.camera.flyTo({
            destination: clickLayer.layerBounds,
            orientation: {
              heading: 0,
              pitch: Cesium.Math.toRadians(-90),
              roll: 0
            }
          })
          break
        case LayerType.Imagery:
          const length = this.viewer.imageryLayers.length
          for (let i = 0; i < length; i++) {
            const item = this.viewer.imageryLayers.get(i).imageryProvider
            if (item.credit && item.credit.html === clickNode.layer_name) {
              this.viewer.camera.flyTo({
                destination: item.rectangle,
                orientation: {
                  heading: 0,
                  pitch: Cesium.Math.toRadians(-90),
                  roll: 0
                }
              })
            }
          }
          break
        case LayerType.Terrain:
          const bound = this.AppX.runtimeConfig.terrain.tilingScheme.rectangle
          this.viewer.camera.flyTo({
            destination: bound,
            orientation: {
              heading: 0,
              pitch: Cesium.Math.toRadians(-90),
              roll: 0
            }
          })
          break
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.widget-LayerList {
  color: white;
  z-index: 100;
}
</style>