<template>
  <div>
    <div class="terrain-switch">
      <el-switch style="color: #fff;" v-model="terrainBtn" size="large" active-text="地形开启" inactive-text="地形关闭"
        @change="swicthTerrainFun" />
    </div>

    <vc-compass :offset="[30, 40]" position="top-right"></vc-compass>
    <vc-zoom-control position="top-right" :offset="[70, 160]" :background="'rgba(0,0,0,0)'"></vc-zoom-control>
    <vc-print position="top-right" :offset="[65, 250]" :show-printView="false" print-automatically size="28px"
      :round="false" :background="'rgba(0,0,0,0)'" color="#fff"></vc-print>
    <vc-status-bar position="bottom-right" :offset="[120, 3]" background="rgba(0,0,0,0.5)"></vc-status-bar>
    <vc-distance-legend position="bottom-right" :offset="[33, 3]" background="rgba(0,0,0,0.5)" bar-background="#F2C037"
      :width="80"></vc-distance-legend>
    <!-- <vc-overlay-html ref="html" :position="[117.186419, 45.66446, 20]" :show="overlayShow">
      1111
    </vc-overlay-html> -->
    <!-- 分析 -->
    <vc-analyses ref="analysesRef" position="top" :main-fab-opts="mfOpts" :offset="[0, 30]" v-if="analysesShow">
      <template #body="drawingActionInstances">
        <div class="measurements-box" v-drag>
          <toolbox :drawingActionInstances="drawingActionInstances" :iconEntity="analysesIcons" @clear="clear"
            @toggle="toggle" @close="analysesShow = false"></toolbox>
        </div>
      </template>
    </vc-analyses>
    <!-- 绘制 -->
    <vc-drawings ref="drawingsCustomRef" position="top" :main-fab-opts="mfOpts" :offset="[0, 60]" v-if="drawShow">
      <template #body="drawingActionInstances">
        <div class="measurements-box" v-drag>
          <toolbox :drawingActionInstances="drawingActionInstances" :iconEntity="drawIcons" @clear="clear"
            @toggle="toggle" @close="drawShow = false"></toolbox>
        </div>
      </template>
    </vc-drawings>
    <!-- 测量 -->
    <vc-measurements ref="measurementsRef" position="top" :main-fab-opts="mfOpts" :offset="[0, 90]" v-if="measureShow">
      <template #body="drawingActionInstances">
        <div class="measurements-box" v-drag>
          <toolbox :drawingActionInstances="drawingActionInstances" :iconEntity="measureIcons" @clear="clear"
            @toggle="toggle" @close="measureShow = false"></toolbox>
        </div>
      </template>
    </vc-measurements>
    <!-- 底图 -->
    <div>

    </div>
    <!-- <vc-primitive-tileset ref="primitive"
      url="http://localhost:90/resource/model/tileset.json"
      @ready="onReady">
      
    </vc-primitive-tileset> -->
    <!-- 工具栏 -->
    <a-row class="toolbox" :gutter="20">
      <a-col class="toolbox-item" @click="changeLayerBoxShow"><svg-icon icon-class="layers" class-name='custom-class' />
        图层</a-col>
      <a-col class="toolbox-item" @click="datasourceShow = !datasourceShow"><svg-icon icon-class="databases"
          class-name='custom-class' /> 添加数据源</a-col>
      <a-col class="toolbox-item">
        <a-dropdown trigger="click">
          <div><svg-icon icon-class="MdiTools" class-name='custom-class' /> 工具 <el-icon><caret-bottom /></el-icon></div>
          <template #overlay>
            <a-menu style="background:rgba(0,0,0,0.5);">
              <a-menu-item @click="analysesShow = !analysesShow"><svg-icon icon-class="bar-chart-vertical-edit"
                  class-name='custom-class' />分析</a-menu-item>
              <a-menu-item @click="drawShow = !drawShow"><svg-icon icon-class="brush-freehand"
                  class-name='custom-class' />绘制</a-menu-item>
              <a-menu-item @click="measureShow = !measureShow"><svg-icon icon-class="angle-tool"
                  class-name='custom-class' />测量</a-menu-item>
              <a-menu-item @click="transformShow = !transformShow"><svg-icon icon-class="IonMove"
                  class-name='custom-class' />移动模型</a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </a-col>
      <a-col class="toolbox-item">
        <a-dropdown trigger="click">
          <div><svg-icon icon-class="IcBaselineRadioButtonChecked" class-name='custom-class' /> 模拟 <el-icon><caret-bottom /></el-icon></div>
          <template #overlay>
            <a-menu style="background:rgba(0,0,0,0.5);">
              <a-menu-item @click="floodAnalysesShow = !floodAnalysesShow"><svg-icon icon-class="IcOutlineWater"
                  class-name='custom-class' />淹没模拟</a-menu-item>                  
              <a-menu-item @click="gateControlShow = !gateControlShow"><svg-icon icon-class="WaterGate"
                  class-name='custom-class' />泄洪模拟</a-menu-item>
              <a-menu-item @click="carOverviewShow = !carOverviewShow"><svg-icon icon-class="MaterialSymbolsLocalTaxi"
                  class-name='custom-class' />路径漫游</a-menu-item>
              <!-- <a-menu-item @click="uavOverviewShow = !uavOverviewShow"><svg-icon icon-class="uav"
                  class-name='custom-class' />无人机</a-menu-item> -->
            </a-menu>
          </template>
        </a-dropdown>
      </a-col>
    </a-row>
    <div class="workspance-input">
      <div>当前工程目录：</div>
      <div class="input-path" @click="$emit('isOpenWorkSpace', true)">{{ pathString == "" ? '未定义' : pathString }}</div>
    </div>
    <!-- 数据源 -->
    <div class="datasource-box dialog_wrap" v-if="datasourceShow" @mousedown.stop="move">
      <Datasource @cancel="datasourceShow = false"></Datasource>
    </div>
    <!-- 图层 -->
    <transition appear name="animate__animated animate__bounce" enter-active-class="animate__fadeInLeft"
      leave-active-class="animate__fadeOutLeft">
      <div class="cesiumlayers-box" v-if="layersShow">
        <CesiumLayers @close="layersShow = false" :modelList="modelList" :serverPath="serverPath" :pathString="pathString"></CesiumLayers>
      </div>
    </transition>

    <!-- 模型变换参数 -->
    <div class="transform-box dialog_wrap" v-if="transformShow"  @mousedown.stop="move">
      <Transform @close="transformShow = false"></Transform>
    </div>
    <!-- 淹没参数 -->
    <div class="transform-box dialog_wrap" v-if="floodAnalysesShow"  @mousedown.stop="move">
      <FloodAnalysis @close="floodAnalysesShow = false"></FloodAnalysis>
    </div>    
    <!-- 闸门参数 -->
    <div class="transform-box dialog_wrap" v-if="gateControlShow"  @mousedown.stop="move">
      <GateControl @close="gateControlShow = false"></GateControl>
    </div>
    <!-- 汽车视角 -->
    <div class="car-box dialog_wrap" v-if="carOverviewShow"  @mousedown.stop="move">
      <CarView @close="carOverviewShow = false" :terrain="terrainBtn"></CarView>
    </div>
    <!-- 无人机视角 -->
    <div class="fly-box dialog_wrap" v-if="uavOverviewShow"  @mousedown.stop="move">
      <UavView @close="uavOverviewShow = false"></UavView>
    </div>
    <!-- 选择工程目录 -->
    <div>
      <el-dialog v-model="props.workspaceShow" :show-close="false" width="480px" :close-on-click-modal="false"
        :align-center="true">
        <template #header>
          <div class="workspace-header">选择工程目录</div>
        </template>
        <Folder :folderList="folderList" :pathList="pathList" @changePath="changePath" @changeBackPath="changeBackPath"
          @handleConfirm="confirmPath" @cancel="$emit('isOpenWorkSpace', false)"></Folder>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref, reactive, getCurrentInstance, ComponentInternalInstance, watch } from "vue";
import toolbox from './toolbox.vue';
import Datasource from './datasource.vue'
import CesiumLayers from "./layers.vue";
import Transform from './transform.vue';
import FloodAnalysis from './floodAnalysis.vue';
import GateControl from './gateControl.vue';
import CarView from './carView.vue';
import UavView from './uavView.vue';
import Folder from './folder.vue';
import { measureIcons, drawIcons, analysesIcons } from './defOpts'
import { getPath, folderMapping, uploadFile, getModelList } from '@/api/map/multidatasource';
import useMapStore from '@/store/modules/maps';
// --------------------------------------------------------------------------------------------------------------------------------------
const proxy = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['workspaceShow']);
const analysesShow = ref<Boolean>(false);
const overlayShow = ref<Boolean>(true);
const datasourceShow = ref<Boolean>(false);
const floodAnalysesShow = ref<Boolean>(false);
const gateControlShow = ref<Boolean>(false);
const carOverviewShow = ref<Boolean>(false);
const uavOverviewShow = ref<Boolean>(false);
const measureShow = ref<Boolean>(false);
const drawShow = ref<Boolean>(false);
const layersShow = ref<Boolean>(false);
const terrainBtn = ref<Boolean>(false);
const transformShow = ref<Boolean>(false);
const folderList = ref<String[]>([]);
const pathList = ref<String[]>([]);
const pathString = ref<String>("");
const modelList = ref<String[]>([]);
const serverPath = ref<String>("");
const otherOpts = reactive({
  offset: [30, 10],
  position: "bottom-right",
});
const mfOpts = reactive({
  direction: 'right'
})
// --------------------------------------------------------------------------------------------------------------------------------------
function clear(drawingActionInstance) {
  if (drawingActionInstance.type == 'drawing')
    proxy.refs.drawingsCustomRef.clearAll();
  else if (drawingActionInstance.type == "measurement")
    proxy.refs.measurementsRef.clearAll();
  else if (drawingActionInstance.type == "analysis")
    proxy.refs.analysesRef.clearAll();
};
function toggle(drawingActionInstance) {
  if (drawingActionInstance.type == 'drawing')
    proxy.refs.drawingsCustomRef.toggleAction(drawingActionInstance.name);
  else if (drawingActionInstance.type == "measurement")
    proxy.refs.measurementsRef.toggleAction(drawingActionInstance.name);
  else if (drawingActionInstance.type == "analysis")
    proxy.refs.analysesRef.toggleAction(drawingActionInstance.name);
}
function swicthTerrainFun(val) {
  let cesium = useMapStore().$state.cesium;
  let viewer = useMapStore().$state.viewer;
  if (val) {
    let terrainLayer = new cesium.CesiumTerrainProvider({
      url: "http://data.marsgis.cn/terrain", // 默认立体地表
    })
    viewer.terrainProvider = terrainLayer;
    viewer.scene.globe.depthTestAgainstTerrain = true;//是否检查深度
  } else {
    viewer.terrainProvider = new cesium.EllipsoidTerrainProvider({});
    viewer.scene.globe.depthTestAgainstTerrain = false;//是否检查深度
  }
}

function changeLayerBoxShow() {
    layersShow.value = !layersShow.value;
}
function move(e) {
  e.stopPropagation();
  let odiv = e.target; //获取目标元素
  if (odiv.className instanceof SVGAnimatedString) {
    return
  }
  if (odiv.className.includes("dialog_wrap")) {
    //算出鼠标相对元素的位置
    let disX = e.clientX - odiv.offsetLeft;
    let disY = e.clientY - odiv.offsetTop;
    document.onmousemove = (e) => {
      //鼠标按下并移动的事件
      //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
      let left = e.clientX - disX;
      let top = e.clientY - disY;

      //绑定元素位置到positionX和positionY上面
      // this.positionX = top;
      // this.positionY = left;

      //移动当前元素
      odiv.style.left = left + "px";
      odiv.style.top = top + "px";
    };
    document.body.onselectstart = document.body.ondrag = () => { return false }
    document.onmouseup = (e) => {
      document.onmousemove = null;
      document.onmouseup = null;
    };
  } else {
    document.onmousemove = null;
    document.onmouseup = null;
    document.body.onselectstart = document.body.ondrag = () => { return true }
  }

}
function getAllDirPath() {

  let pathName = " ";
  getPath({ pathName: pathName }).then(res => {
    if (res.code == 200) {
      folderList.value = res.data.folderList;
    }
  })
}
// 当路径改变时，重新请求新的目录列表
function changePath(val: String[]) {
  for (let v of val) {
    if (v != "") {
      pathList.value.push(v);
    }
  }
  let pathName;
  if (pathList.value.length == 0) {
    pathName = " ";
  } else if (pathList.value.length == 1) {
    pathName = pathList.value[0] + '/';
  }
  else {
    pathName = pathList.value.join('/');
  }
  getPathByName(pathName);
}
// 根据路径名查询目录
function getPathByName(pathName) {
  getPath({ pathName: pathName }).then(res => {
    if (res.code == 200) {
      let forlist = res.data.folderList;
      let list: Array<String> = [];
      if (pathName == " ") {
        folderList.value = forlist;
        pathList.value = [];
      } else {
        for (let f of forlist) {
          f = f.includes("\\") ? f.split('\\') : f.split('/');
          f = f[f.length - 1];
          list.push(f);
        }
        folderList.value = list;
      }
    }
  })
}
// 回退路径事件
function changeBackPath(val) {
  let pathName;
  pathList.value = val;
  if (pathList.value.length == 0) {
    pathName = " ";
  } else if (pathList.value.length == 1) {
    pathName = " ";
  }
  else {
    pathName = pathList.value.join('/');
  }
  getPathByName(pathName);
}
// 当点击确认路径按钮时
function confirmPath() {
  pathString.value = pathList.value.join('\/');
  useMapStore().setWorkspace(pathString.value);
  if (pathString.value == "") {
    return
  } else {
    getModelList({ folderName: pathString.value }).then(res => {
      console.log(res);
      modelList.value = res.data;
      serverPath.value = res.msg;
    })
  }
  proxy.emit('isOpenWorkSpace', false);
}

getAllDirPath();
</script>

<style scoped  lang="scss">
// 工具栏
.toolbox {
  position: absolute;
  left: 20px;
  top: 10px;
  background-color: rgba(0, 0, 0, 0.5);
  box-shadow: 0px 0px 10px rgba(255, 255, 255, 0.2);
  // width: 60px;
  height: 50px;
  text-align: center;
  line-height: 50px;
  color: #fff;
  cursor: pointer;
  z-index: 66;

  .toolbox-item {
    transition: all 0.5 linear;
  }

  .toolbox-item:hover {
    background: rgba(0, 0, 0, 0.8);
    color: yellow;
    background-color: rgba(255, 255, 255, 0.2);
  }

}

.layer {
  position: absolute;
  left: 80px;
  top: 20px;
  width: 300px;
  height: 500px;
  background-color: #fff;

  .layer-header {
    width: 100%;
    height: 50px;
    text-align: center;
    color: #000;
    font-size: 18px;
    line-height: 50px;
    position: relative;

    .close {
      position: absolute;
      top: -4px;
      right: 9px;
      font-size: 30px;
      cursor: pointer;
    }

    .close:hover {
      color: #1890FF;
    }
  }

  .layer-content {
    width: 100%;
    padding: 8px;
    margin: 0 auto;
  }
}

.measurements-box {
  position: absolute;
  left: 50%;
  transform: translate(-50%, 0);
  cursor: pointer;
}

.custom-class {
  font-size: 18px;
}

.datasource-box {
  position: fixed;
  left: calc(50vw - 200px);
  top: 200px;
  // transform: translate(-50%,-0%);
  width: 400px;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 12;
  padding: 10px;
  box-shadow: 0 0 2px rgba($color: #fff, $alpha: 0.7);
  cursor: move;
}

.cesiumlayers-box {
  position: absolute;
  left: 20px;
  top: 80px;
  width: 200px;
  z-index: 12;
  box-shadow: 0 0 2px rgba(255, 255, 255, 1);
  visibility: visible;
}

.close-box {
  color: #fff;
  text-align: right;
}

.terrain-switch {
  position: absolute;
  right: 230px;
  top: 10px;
  z-index: 10;
}

.workspance-input {
  position: absolute;
  left: 371px;
  top: 25px;
  z-index: 10;
  display: flex;
  color: #fff;

  .input-path {
    cursor: pointer;
  }

  .input-path:hover {
    text-decoration: underline;
  }
}

.transform-box {
  width: 210px;
  position: absolute;
  top: 100px;
  right: 200px;
  background-color: rgba(0, 0, 0, 0.5);
  box-shadow: 0 0 2px #fff;
  z-index: 20;
  padding: 10px;
  cursor: move;
}

.car-box{
  width: 390px;
  position: absolute;
  top: 325px;
  right: 100px;
  background-color: rgba(0, 0, 0, 0.5);
  box-shadow: 0 0 2px #fff;
  z-index: 20;
  padding: 10px;
  cursor: move;
}

.fly-box{
  width: 300px;
  position: absolute;
  top: 325px;
  right: 100px;
  background-color: rgba(0, 0, 0, 0.5);
  box-shadow: 0 0 2px #fff;
  z-index: 20;
  padding: 10px;
  cursor: move;
}
.workspace-header {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  font-family: '黑体';

}

:deep(.ant-dropdown-menu-item, .ant-dropdown-menu-submenu-title) {
  color: #fff;
}

:deep(.ant-dropdown-menu-item:hover) {
  color: #000;
}
</style>