<template>
  <div id="wrapper">
    <div class="layerBox">
      <div class="layer-title" @click="openTree">
        <i class="el-icon-menu icon-setting"></i><span class="layer-text">图层</span>
      </div>
      <!-- node-key 这里会决定树的判断方式，影响选择框-->
      <el-tree
        ref="layerTree"
        class="layerTree"
        :data="legendList"
        show-checkbox
        node-key="name"
        :render-after-expand="false"
        :props="defaultProps"
        :default-checked-keys="checkList"
        :render-content="renderContent"
        @check-change="handleCheckChange">
      </el-tree>
    </div>
  </div>
</template>

<script>
  import facilityModel from './model/facilityModel';
  import eventHelper from "./utils/eventHelper";
  export default {
    name: 'layer-control',
    data: function () {
      return {
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        legendList: [],
        checkList: [],
        isExpanded: false,
      }
    },
    mounted: function () {
    },
    methods: {
      getLayerTree: function () {
        return this.$refs.layerTree;
      },
      init: function (mapComponent, customerLayers, type, mapConfigHelper) {
        this.mapComponent = mapComponent;
        var list = facilityModel.getAllFacilityTypeConfig();
        var legendItem = [];
        list.forEach(function (facilityConfig, index) {
          var facility = {
            id: facilityConfig.id,
            title: facilityConfig.name,
            facilityTypeName: facilityConfig.facilityTypeName,
            icon: facilityConfig.icon,
            showIcon: facilityConfig.showIcon == 1,
            showSub: false
          };
          if (facility.showIcon) {
            this.checkList.push(facilityConfig.name);
          }
          legendItem.push(facility);
          // eventHelper.emit('openMapLegend', facility);
        }.bind(this));
        this.legendList = [];
        var layerTree = {};
        var self = this;
        var layersGroup = [];
        if (type == 1) {
          if (legendItem.length > 0) {
            this.legendList.push({
              id: 1,
              title: '测站',
              showIcon: true,
              showSub: false,
              children: legendItem
            })
          }
          var baseMapConfig = mapConfigHelper.getBaseConfig();
          baseMapConfig.forEach(function (config) {
            if (config.name.toLowerCase() !== 'basemap') {
              layersGroup.push(config)
            }
          })
          function getLayers(layers) {
            layers.forEach((item) => {
              if (!!item.children) {
                getLayers(item.children);
              } else {
                if (!!item.layer) {
                  item['icon'] = item.layer.icon1;
                }
                item['showIcon'] = item.layer.display == 1;
                item['showSub'] = false;
                item['isAdd'] = item.layer.display == 1;
                if (item.display == 1) {
                  self.checkList.push(item.name);
                }
              }
            })
          }

          getLayers(layersGroup);
          this.legendList = layersGroup;
        }
      },
      // 勾选树节点触发方法
      handleCheckChange: function (data, checked, indeterminate) {
        if (!!indeterminate) {
          return;
        }
        data.showIcon = checked;
        this.$refs.layerTree.$emit('treeChange', data);
        // 改变子孙节点
        let changeTreeChildren = (treeChildren) => {
          treeChildren.forEach((layerConfig) => {
            if (layerConfig.type == 'Layer') {
              //点击的是设备图层
              if (layerConfig.layer.bizType == 'device') {
                layerConfig.showIcon = checked;
                this.$parent.$emit('openMapLegend', layerConfig);
              }
              else if (!!checked) {
                this.$parent.$emit('map:show-layer', layerConfig.layer.funId);
              } else {
                this.$parent.$emit('map:hide-layer', layerConfig.layer.funId);
              }
            }
            if(layerConfig.children && layerConfig.children.length) changeTreeChildren(layerConfig.children)
          })
        }
        if (!!data.children && data.children.length > 0) {
          changeTreeChildren(data.children)
          if (!!checked) {
            this.$parent.$emit('map:show-layer-group', data);
          } else {
            this.$parent.$emit('map:hide-layer-group', data);
          }
        } else if (!indeterminate && data.layer.bizType == 'device') {
          this.$parent.$emit('openMapLegend', data);
        }
        else if (data.type == 'Layer') {
          if (!!checked) {
            this.$parent.$emit('map:show-layer', data.layer.funId);
            this.$parent.$emit('map:show-layer-detail', data.layer);
          } else {
            this.$parent.$emit('map:hide-layer', data.layer.funId);
            this.$parent.$emit('map:hide-layer-detail', data.layer);
          }
        } else if (data.facilityTypeName == 'facilityLayer') {
          this.changeAllSubLayer(data, checked, indeterminate);
        } else {
          if (!indeterminate && !!data.facilityTypeName) {
            this.$parent.$emit('openMapLegend', data);
          }
        }
      },
      changeAllSubLayer(data, checked, childHasCheck)
      {
        if (data.children && !childHasCheck) {
          //遍历所有子节点更新显隐
          this.setAllSubLayerVisible(data, checked);
        } else if (!data.children) {
          //只需要更新当前节点的显隐
          this.setLayerVisible(data, checked);
        }
      }
      ,
      setLayerVisible(data, visible){
        var facilityMapLayer = this.mapComponent.getLayerById("pipeline");
        for (var i = 0; i < data.layerId.length; i++) {
          var sublayer = facilityMapLayer.findSublayerById(data.layerId[i]);
          sublayer.visible = !sublayer.visible;
        }
        facilityMapLayer.refresh();
      },
      getLayerVisible(layerName){
        var layerTree = this.$refs.layerTree;
        var nodes = layerTree.store._getAllNodes();
        var layer = nodes.find(function (node) {
          return node.label == layerName;
        })
        return layer.checked
      },
      setAllSubLayerVisible(data, visible)
      {
        var facilityMapLayer = this.mapComponent.getLayerById("pipeline");
        this.recursiveSetLayerVisible(facilityMapLayer.sublayers, {data, visible});
        facilityMapLayer.refresh();
      }
      ,
      recursiveSetLayerVisible(subLayer, param)
      {
        var recursiveSetLayerVisible = this.recursiveSetLayerVisible;
        subLayer.forEach(function (item) {
          if (item.id == this.param.data.layerId) {
            item.visible = true;
          }
          if (item.sublayers)
            this.recursiveSetLayerVisible(item.sublayers, this.param);
        }, {param, recursiveSetLayerVisible});
      }
      ,
      renderContent(h, {node, data, store})
      {
        if (!data.icon) {
          data.icon = 'default';
        }
        let icon = './img/mapLegend/facility/' + data.icon + '.png';
        /*if (data.facilityTypeName == 'layer') {
         icon = './img/mapLegend/layer/defaultLayer.png';
         }*/
        let showIcon = data.showIcon;
        if (!!data.children) {
          return h('span', null, node.label);
        } else {
          return h('span', null, [h('span', null, node.label), h('span', {style: "float: right; margin: 5px"}, [h('img', {
            attrs: {
              src: icon,
              width: '20px',
              height: '24px',
            }
          })])]);
        }
      },
      openTree: function () {
        if (!this.$refs.layerTree) return;
        var nodes = this.$refs.layerTree.store._getAllNodes();
        for (var i = 0, len = nodes.length; i < len; i++) {
          nodes[i].expanded = !(this.isExpanded);
        }
        this.isExpanded = !this.isExpanded;
      }
    }
  }
</script>

<style>
  .layerBox {
    min-width: 13em;
    max-width: 18em;
    background: #fff;
    border-radius: 5px;
    text-align: left;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, .2);
    position: absolute;

  }

  .layerBox .el-tree-node {
    line-height: 30px;
    min-height: 30px;
  }

  .layer-title {
    background: #157DD6;
    text-align: center;
    color: #fff;
    height: 2.8em;
    line-height: 2.8em;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
  }

  .layer-text {
    margin-left: 0.5em;
  }

  .layerTree {
    border: none;
    overflow: auto;
  }
</style>
