<!--
 * @Descripttion: 
 * @version: 
 * @Author: ysh
 * @Date: 2023-06-25 16:27:07
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-07-11 14:58:39
-->
<template>
  <div v-loading="loading" element-loading-background="rgba(122, 122, 122, 0.8)" element-loading-text="正在读取数据，请稍等...">
    <div class="header">
      图层信息
      <svg-icon icon-class="MaterialSymbolsCloseRounded" class-name='close' @click="$emit('close')" />
    </div>
    <div class="tree-main">
      <el-scrollbar height="400px">
        <a-tree :showLine="true" checkable defaultExpandAll v-model:checkedKeys="checkedKeys"
          v-model:selectedKeys="selectedKeys" :tree-data="treeData" @check="handleCheckTree" @select="handleSelect">
        </a-tree>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup lang="ts" name="CesiumLayers">
import { ref, onMounted, watch, toRaw } from 'vue';
import useMapStore from '@/store/modules/maps';
import { addModel, getModel, listModel, updateModel, delModel } from '@/api/map/model';
import { folderMapping, getModelList } from '@/api/map/multidatasource';
import { fa } from 'element-plus/es/locale';
import ImageLayer from 'ol/layer/Image';
interface propsChildren {
  title: String,
  key: String,
  layer: any
}
const props = defineProps(['modelList', 'serverPath', 'pathString']);
const { proxy } = getCurrentInstance();
const loading = ref<Boolean>(true);
const checkedKeys = ref<string[]>(['0']);
const selectedKeys = ref<string[]>([]);
const treeData = ref([
  {
    title: '地球底图',
    key: '0',
    children: []
  },
  {
    title: '数据图层',
    key: '1',
    children: [],
  }
]);
const primitives = ref<any>([]);
const datasources = ref<any>([]);
const removable = ref<Boolean>(false);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: null,
  address: null,
  heading: null,
  pitch: null,
  roll: null,
  positionX: null,
  positionY: null,
  positionZ: null,
  selected: null,
  type: null
});
let cesium = useMapStore().$state.cesium;
let viewer = useMapStore().$state.viewer;
// https://gac-geo.googlecnapps.cn/maps/vt?lyrs=s&gl=CN
onMounted(() => {
  // console.log(viewer.imageryLayers._layers)
  // console.log(viewer.scene.primitives._primitives.length)
  // console.log(viewer.dataSources._dataSources.length)
  initTreeData();
})
watch(() => props.modelList, (newValue, oldValue) => {
  clean();
  treeData.value = [
    {
      title: '地球底图',
      key: '0',
      children: []
    },
    {
      title: '数据图层',
      key: '1',
      children: [],
    }
  ];
  initTreeData();
})
watch(() => props.pathString, (newValue, oldValue) => {

})
function clean() {
  for (let i = 2; i < viewer.imageryLayers._layers.length; i++) {
    viewer.imageryLayers.remove(viewer.imageryLayers._layers[i])
  }
  viewer.entities.removeAll();
  for (let l of viewer.scene.primitives._primitives) {
    viewer.scene.primitives.remove(l)
  }
  for (let l of viewer.dataSources._dataSources) {
    viewer.dataSources.remove(l)
  }
};
function initTreeData() {
  let imageryLayers = viewer.imageryLayers._layers;
  let imageryArr = [];
  for (let i = 0; i < imageryLayers.length; i++) {
    let layerObj = <propsChildren>{};
    if (i == 0) {
      layerObj.title = '初始底图'
    } else {
      let t = imageryLayers[i].imageryProvider.credit.html;
      if (t.includes("本地影像")) {
        continue
      } else {
        layerObj.title = t;
      }
    }
    layerObj.key = '0-' + i;
    layerObj.layer = imageryLayers[i];
    imageryArr.push(layerObj);
  }
  treeData.value[0].children = imageryArr;
  loading.value = true;
  getDataLayers();
  if (props.pathString == "") {
    loading.value = false;
  }
}

function handleCheckTree(checkedKeys, nodesObj) {
  if (!nodesObj.node.children) {
    if (nodesObj.node.layer instanceof cesium.Cesium3DTileset || nodesObj.node.layer instanceof cesium.ImageryLayer) {
      nodesObj.node.layer.show = nodesObj.checked;
    }
    else if (nodesObj.node.title.search(/\.(kml)$/i) != -1) {
      if (nodesObj.checked) {
        let flag = false;
        for (let l of viewer.dataSources._dataSources) {
          if (l.name == nodesObj.node.title)
            flag = true;
        }
        if (flag == false) {
          let url = window.location.origin + '/resource/model' + nodesObj.node.title;
          addKmlDatasource(url, nodesObj.node.title, 0);
        }
      }
      else {
        for (let l of viewer.dataSources._dataSources) {
          if (l.name == nodesObj.node.title)
            viewer.dataSources.remove(l)
        }
      }
    }
  }
  else {
    if (nodesObj.node.key == "0") {
      for (let l of viewer.imageryLayers._layers) {
        l.show = nodesObj.checked
      }
    }
    else {
      for (let n of nodesObj.node.children) {
        if (n.layer instanceof cesium.Cesium3DTileset) {
          n.layer.show = nodesObj.checked;
        }
        else if (n.title.search(/\.(kml)$/i) != -1) {
          if (nodesObj.checked) {
            let flag = false;
            for (let l of viewer.dataSources._dataSources) {
              if (l.name == n.title)
                flag = true;
            }
            if (flag == false) {
              let url = window.location.origin + '/resource/model' + n.title;
              addKmlDatasource(url, n.title, 0);
            }
          }
          else {
            for (let l of viewer.dataSources._dataSources) {
              if (l.name == n.title)
                viewer.dataSources.remove(l)
            }
          }
        }
      }
    }
  }
}

function handleSelect(selectedKeys, nodeObj) {
  if (nodeObj.node.layer instanceof cesium.Cesium3DTileset) {
    nodeObj.node.layer.show = nodeObj.selected;
    viewer.flyTo(nodeObj.node.layer);
  } else if (nodeObj.node.title.search(/\.(kml)$/i) != -1) {
    let flag = false;
    for (let l of viewer.dataSources._dataSources) {
      if (l.name == nodeObj.node.title) {
        flag = true;
        viewer.flyTo(toRaw(l));
      }
    }
    if (flag == false) {
      let url = window.location.origin + '/resource/model' + nodeObj.node.title;
      addKmlDatasource(url, nodeObj.node.title, 1);
    }
  }  
  checkedKeys.value.push(nodeObj.node.key);
}
function getDataLayers() {
  if (props.modelList.length == 0) {
    loading.value = true;
  } else {
    for (let l of props.modelList) {
      if (l.includes('tileset.json')) {
        let url = window.location.origin + '/resource/model' + l;
        // let url = props.serverPath + '/resource/model' + l;
        add3DTileset(url, l, "", "")
      } else if (l.includes('tilemapresource.xml')) {
        l = l.split('/');
        l = l.slice(0, l.length - 1).join('/');
        let url = window.location.origin + '/resource/model' + l + '/{z}/{x}/{y}.png';
        addImagery(url);
      } else if (l.search(/\.(kml)$/i) != -1) {
        let url = window.location.origin + '/resource/model' + l;
        addKmlTree(url, l);
      }
    }
  }
}

function add3DTileset(url, name, featureIdLabel, instanceFeatureIdLabel) {
  let tileset = new cesium.Cesium3DTileset({
    url: url,
    show: false,
    featureIdLabel: featureIdLabel,
    instanceFeatureIdLabel: instanceFeatureIdLabel,
    skipLevelOfDetail: false,
    skipLevels: 0,
  });
  // 异步加载模型

  let tilesetObj = <propsChildren>{};
  tileset.readyPromise.then(function (model) {
    viewer.scene.primitives.add(model);
    let center = model.boundingSphere.center;
  })
  tilesetObj.key = '1-' + treeData.value[1].children.length;
  tilesetObj.title = name.replace('/tileset.json', '');
  tilesetObj.layer = tileset;
  treeData.value[1].children.push(tilesetObj);
  loading.value = false;
}

function addImagery(url) {
  let imageryProvider = new cesium.UrlTemplateImageryProvider({
    url: url,
    maximumLevel: 22,
    credit: "本地影像"
  });
  viewer.imageryLayers.addImageryProvider(imageryProvider);
  let imageryObj = <propsChildren>{};
  imageryObj.title = "本地影像";
  imageryObj.key = '0-' + treeData.value[0].children.length;
  imageryObj.layer = viewer.imageryLayers._layers[treeData.value[0].children.length];
  treeData.value[0].children.push(imageryObj)
}

function addKmlTree(url, name) {
  let kmlObj = <propsChildren>{};
  kmlObj.key = '1-' + treeData.value[1].children.length;
  kmlObj.title = name;
  treeData.value[1].children.push(kmlObj);
  loading.value = false;
}

function addKmlDatasource(url, name, fly) {
  const options = {
    camera: viewer.scene.camera,
    canvas: viewer.scene.canvas
  };
  cesium.KmlDataSource.load(url, options).then(kml => {
    kml.name = name;
    viewer.dataSources.add(kml);
    if (fly) {
      viewer.flyTo(kml);
    }
  });

}
</script>

<style scoped lang="scss">
.header {
  width: 100%;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background-color: rgba($color: #151515, $alpha: 0.8);
  color: #fff;
  letter-spacing: 2px;
  // font-weight: bold;
  font-family: '微软雅黑';
  position: relative;
}

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

.close:hover {
  color: yellow;
}

.tree-main {
  height: 400px;
  background: rgba(0, 0, 0, 0.6);
}

:deep(.ant-tree) {
  color: #fff;
  background: transparent;
}

:deep(.ant-tree-show-line .ant-tree-switcher) {
  background: transparent;
}

:deep(.ant-tree .ant-tree-node-content-wrapper.ant-tree-node-selected) {
  background: rgba(#fff, 0.4);
  color: #F4E04D;
}

:deep(.ant-tree .ant-tree-node-content-wrapper:hover) {
  background-color: rgba(#fff, 0.4);
  color: #b1e1ff;
}
</style>