<!--
 * @Descripttion: 
 * @version: 
 * @Author: ysh
 * @Date: 2023-05-09 17:31:06
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-06-28 14:14:21
-->
<template>
  <div class="layers-box">
    <a-row justify="center" class="title">图层信息<svg-icon icon-class="MaterialSymbolsCloseRounded" class-name='close'
        @click="$emit('close')" /></a-row>
    <a-tree v-model:expandedKeys="expandedKeys" v-model:checkedKeys="checkedKeys" v-model:selectedKeys="selectedKeys"
      multiple :tree-data="treeData" checkable @check="handleChangeVisible" @rightClick="onRightClick" @select="onSelect"
      style="height:450px; overflow-y: scroll;">
      <template #title="{ key: treeKey, title }">
        <a-dropdown :trigger="['contextmenu']">
          <span>{{ title }}</span>
          <template #overlay>
            <a-menu @click="({ item: item, key: menuKey }) => onContextMenuClick(treeKey, menuKey, item)">
              <a-menu-item key="1" @click="() => removeLayer(treeKey)" :disabled=removable>移除</a-menu-item>
              <a-menu-item key="2" @click="() => openTable(treeKey)" :disabled=opentableable>打开属性表</a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
    </a-tree>
  </div>
</template>

<script setup lang="ts">
import type { TreeProps } from 'ant-design-vue';
import useMapStore from '@/store/modules/maps';
import TileLayer from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector';
import { getCurrentInstance, ref } from 'vue';
const maps = useMapStore().$state.olmap;
const layers = ref<any>([]);
const expandedKeys = ref<string[]>(['0']);
const checkedKeys = ref<string[]>(['0-0-2', '0-1']);
const selectedKeys = ref<string[]>([]);
const treeData: TreeProps['treeData'] = [];
const removable = ref(false);
const opentableable = ref(false);
const { proxy } = getCurrentInstance();
function getTileLayers() {
  layers.value = maps?.getAllLayers();

  let obj = {
    title: '地图图层',
    key: '0',
    layers: layers.value,
    children: [],
  }
  let imgobj = {
    title: '影像图层',
    key: '0-0',
    children: [],
  }
  obj.children.push(imgobj);
  for (let l of layers.value) {
    let layersObj: any = {
        title: l.getProperties().name,
        key: l.getProperties().key,
        isLeaf: true,
        layers: l
      }   
    if (l instanceof TileLayer && l.getProperties().key.startsWith('0-0'))      
      imgobj.children.push(layersObj);
    if (l instanceof TileLayer && l.getProperties().key.startsWith('0-1'))      
      obj.children.push(layersObj);
  }
  treeData?.push(obj);
}
function getVectorLayers() {
  layers.value = maps?.getAllLayers();
  let vectorObj = {
    title: '矢量图层',
    key: '1',
    layers: layers.value,
    children: [],
  }
  treeData?.push(vectorObj);
  for (let l of layers.value) {
    if (l instanceof VectorLayer) {
      let index = layers.value.indexOf(l);
      if (index < 2) {
        index = 2
      }
      let vector: any = {
        title: l.title,
        key: '1-' + (index - 2),
        isLeaf: true,
        layers: l
      }
      checkedKeys.value.push(vector.key)
      expandedKeys.value.push("1")
      vectorObj.children.push(vector);
    }
  }
}
function onRightClick(nodes) {
  if (nodes.node.key.startsWith("1"))
    removable.value = false
  else
    removable.value = true
  opentableable.value = removable.value

}
function onSelect() {
  layers.value = maps?.getAllLayers();
  let leafName = "";
  treeData[1].children.forEach(element => {
    if (element.key == selectedKeys._value[0]) {
      leafName = element.title
    }
  });
  for (let l of layers.value) {
    if (l instanceof VectorLayer) {
      if (l.title == leafName)
        maps?.getView().fit(l.getSource()?.getExtent());
    }
  }
}
function handleChangeVisible(checkedKeys, nodes) {
  let layers = nodes.node.layers;
  if (layers instanceof Array) {
    if (nodes.node.key == "1") {
      for (let layer of layers)
        if (layer instanceof VectorLayer)
          layer.setVisible(nodes.checked)
    }
    else {
      for (let layer of layers)
        if (layer instanceof TileLayer)
          layer.setVisible(nodes.checked)
    }
  }
  else {
    if (layers instanceof TileLayer) {
      layers.setVisible(nodes.checked)
    } else if (layers instanceof VectorLayer) {
      layers.setVisible(nodes.checked)
    }
  }
}
const removeLayer = (treeKey: string) => {
  layers.value = maps?.getAllLayers();
  let leafName = "";
  treeData[1].children.forEach(element => {
    if (element.key == treeKey) {
      leafName = element.title
    }
  });
  for (let l of layers.value) {
    if (l instanceof VectorLayer) {
      if (leafName == "" || l.title == leafName) {
        maps?.removeLayer(l)
      }
    }
  }
};
const openTable = (treeKey: string) => {
  if (treeKey.startsWith("1-")) {
    proxy.$emit('opentableable', opentableable.value)
    layers.value = maps?.getAllLayers();
    let data = [];
    let name = "";
    treeData[1].children.forEach(element => {
      if (element.key == treeKey) {
        name = element.title
        data = element.layers
      }
    });
    proxy.$emit('returntableData', data)
    proxy.$emit('returntableName', name)
  }
};
const onContextMenuClick = (treeKey: string, menuKey: string | number, item) => {
  // console.log(`treeKey: ${treeKey}, menuKey: ${menuKey}`);
  // console.log(selectedKeys)
};
getTileLayers();
getVectorLayers();

</script>

<style scoped>
.title {
  line-height: 50px;
  font-size: 16px;
  font-family: '微软雅黑';
  background-color: #151515;
  color: #fff;
  position: relative;
}

.close {
  font-size: 20px;
  position: absolute;
  right: 5px;
  top: 8px;
  cursor: pointer;
}

.close:hover {
  color: yellow;
}
</style>