<template>
  <div id="maplayer">
    <div id="layerControl" class="layerControl">
      <div class="title">
        <label>图层列表</label>
      </div>
      <ul id="layerTree" class="layerTree" ref="layerTree"></ul>
    </div>
  </div>
</template>

<script>
export default {
  name: 'bs-layer',
  render () { },
  props: {
    anchor: {
      type: String
    },
    offset: {
      type: Object
    }
  },
  data () {
    return {
      layerName: [],
      layerVisibility: [],
      layerArr: []
    }
  },
  watch: {
  },
  methods: {
    loadLayersControl () {
      const { layerName, layerVisibility, layerArr } = this
      var treeContent = this.$refs.layerTree// 图层目录容器
      var layers = this.$parent.getAllLayers() // 获取地图中所有图层
      for (let [i, layer] of layers.entries()) {
        // 获取每个图层的名称、是否可见属性
        layerArr[i] = layer
        layerName[i] = layer.get('name')
        layerVisibility[i] = layer.getVisible()

        // 新增li元素，用来承载图层项
        var elementLi = document.createElement('li')
        treeContent.appendChild(elementLi) // 添加子节点
        // 创建复选框元素
        var elementInput = document.createElement('input')
        elementInput.type = 'checkbox'
        elementInput.name = 'layers'
        elementLi.appendChild(elementInput)
        // 创建label元素
        var elementLable = document.createElement('label')
        elementLable.className = 'layer'
        // 设置图层名称
        this.setInnerText(elementLable, layerName[i])
        elementLi.appendChild(elementLable)

        // 设置图层默认显示状态
        if (layerVisibility[i]) {
          elementInput.checked = true
        }
        this.addChangeEvent(elementInput, layer)  // 为checkbox添加变更事件
      }
    },
    addChangeEvent (element, layer) {
      element.onclick = function () {
        if (element.checked) {
          layer.setVisible(true)
        } else {
          layer.setVisible(false)
        }
      }
    },
    setInnerText (element, text) {
      if (typeof element.textContent === 'string') {
        element.textContent = text
      } else {
        element.innerText = text
      }
    }
  },
  mounted () {
    this.$parent.$on('ready', (config) => {
      this.ol = config.ol // 获取地图命名空间----
      this.map = config.map // 获取地图对象------
      this.loadLayersControl()
    })
  }
}
</script>
 <style scoped>
#maplayer {
  width: 300px;
  position: absolute;
  min-width: 200px;
  max-height: 200px;
  right: 0px;
  top: 150px;
  color: #ffffff;
  background-color: #4c4e5a;
  z-index: 2001;
  border-radius: 10px;
  /*圆角的大小 */
  border-color: #000
  /*边框颜色*/
}

























/* 图层控件层样式设置 */

.layerControl {
  width: 100%;
}

.layerControl .title {
  font-weight: bold;
  font-size: 15px;
  margin: 10px;
}

.layerTree li {
  list-style: none;
  margin: 5px 10px;
}
</style>
