<template>
  <div  class="dialog_content">
    <div class="header">
      <h3>参数设置</h3>
      <div class="close" @click="$emit('close')">×</div>
    </div>
    <div class="content">
      <el-row class="content-item">
        <el-col :span="10">最大高度(米):</el-col>
        <el-col :span="8">
          <a-input-number v-model:value="maxHeight" size="small" :step="10" />
        </el-col>
      </el-row>
      <el-row class="content-item">
        <el-col :span="10">最小高度(米):</el-col>
        <el-col :span="8">
          <a-input-number v-model:value="minHeight" size="small" :step="10" />
        </el-col>
      </el-row>
      <el-row class="content-item">
        <el-col :span="10">淹没时间(秒):</el-col>
        <el-col :span="8">
          <a-input-number v-model:value="floodSpeed" size="small" :step="5" />
        </el-col>
      </el-row>
      <el-row class="content-item">
        <a-button @click="draw()">绘制图形</a-button>
        <a-upload :accept="acceptType" :showUploadList="false" :customRequest="customUpload">
          <a-button style="margin-left: 15px;">
            导入
          </a-button>
        </a-upload>
      </el-row>
      <el-row class="content-item">
        <a-button @click="flood()">开始淹没</a-button>
        <a-button @click="clean()" style="margin-left: 15px;">清除</a-button>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, getCurrentInstance } from 'vue';
import shp from 'shpjs/dist/shp';
import useMapStore from '@/store/modules/maps';
const acceptType = ref(".zip, .kml, .geojson, .json");
const maxHeight = ref(3890);
const minHeight = ref(3880);
const floodSpeed = ref(10);
let viewer = useMapStore().$state.viewer;
let cesium = useMapStore().$state.cesium;
function customUpload(file) {
  if (file.file.name.includes('geojson') || file.file.name.includes('json')) {
    const f = URL.createObjectURL(file.file);
    viewer.dataSources.add(cesium.GeoJsonDataSource.load(f, {
      stroke: new cesium.Color.fromCssColorString("#ffffff"),
      fill: new cesium.Color.fromCssColorString("#ffffff").withAlpha(0.1),
      clampToGround: true
    })).then(geojson => {
      geojson.name = "floodRange";
      let polygonHierarchy = geojson.entities.values[0].polygon.hierarchy.getValue().positions;
      let tempPoints = [];
      for (let i = 0; i < polygonHierarchy.length - 1; i++) {
        tempPoints.push(polygonHierarchy[i])
      }
      adapCoordi = tempPoints;
    });
  }
  if (file.file.name.includes('kml')) {
    const f = URL.createObjectURL(file.file);
    viewer.dataSources.add(cesium.KmlDataSource.load(f,
      {
        stroke: new cesium.Color.fromCssColorString("#ffffff"),
        fill: new cesium.Color.fromCssColorString("#ffffff").withAlpha(0.1),
        clampToGround: true
      }
    )).then(kml => {
      kml.name = "floodRange";
      let polygonHierarchy = [];
      for (let entity of kml.entities.values) {
        if (entity.polygon != undefined) {
          polygonHierarchy = entity.polygon.hierarchy.getValue().positions;
          break;
        }
      }
      let tempPoints = [];
      for (let i = 0; i < polygonHierarchy.length - 1; i++) {
        tempPoints.push(polygonHierarchy[i])
      }
      adapCoordi = tempPoints;
    });
  }
  if (file.file.name.includes('zip')) {
    const reader = new FileReader();
    const fileData = file.file;
    reader.readAsArrayBuffer(fileData);
    reader.onload = function (e) {
      shp(e.target?.result).then(geojson => {
        viewer.dataSources.add(cesium.GeoJsonDataSource.load(geojson, {
          stroke: new cesium.Color.fromCssColorString("#ffffff"),
          fill: new cesium.Color.fromCssColorString("#ffffff").withAlpha(0.1),
          clampToGround: true
        })).then(geojson => {
          geojson.name = "floodRange";
          let polygonHierarchy = geojson.entities.values[0].polygon.hierarchy.getValue().positions;
          let tempPoints = [];
          for (let i = 0; i < polygonHierarchy.length - 1; i++) {
            tempPoints.push(polygonHierarchy[i])
          }
          adapCoordi = tempPoints;
        });
      });
    }
  }
};
function clean() {
  viewer.entities.removeAll();
  for (let l of viewer.scene.primitives._primitives) {
    if (l._instanceIds == "floodGeoInstance")
      viewer.scene.primitives.remove(l)
  }
  for (let l of viewer.dataSources._dataSources) {
    if (l.name == "floodRange")
      viewer.dataSources.remove(l)
  }
};
var adapCoordi;
//淹没分析
function flood() {
  if (cesium.defined(adapCoordi)) {
    //viewer.flyTo(viewer.entities.getById("floodPolygon"));
  } else {
    alert("请先绘制淹没范围");
    return;
  }
  var currentHeight = minHeight.value;
  var maxHeigh = maxHeight.value;
  var times = floodSpeed.value;
  var speed = (maxHeigh - currentHeight) / times;
  // //entity方式创建.
  // let entity = viewer.entities.add({
  //   id: "floodEntity",
  //   polygon: {
  //     //hierarchy: cesium.Cartesian3.fromDegreesArrayHeights(adapCoordi),
  //     hierarchy: adapCoordi,
  //     closeTop: true,
  //     closeBottom: true,
  //     fill: true,
  //     //获取或设置分类类型属性，指定此多边形在地面上时是否对地形、3D瓷砖或两者进行分类。
  //     classificationType: cesium.ClassificationType.BOTH,
  //     material: cesium.Color.fromAlpha(cesium.Color.fromCssColorString("#3b5740"), 0.9),
  //     perPositionHeight: true,
  //     //一个属性，其值由回调函数延迟评估。time, result
  //     extrudedHeight: 0,
  //   },
  // });
  // //设置高度随时间变化
  // var setFlood = setInterval(() => {
  //   if (currentHeight < maxHeigh) {
  //     currentHeight += speed / 30;
  //     entity.polygon.extrudedHeight = new cesium.CallbackProperty(function (time, result) {
  //       return currentHeight;
  //     }, false);
  //     if (currentHeight > maxHeigh) {
  //       currentHeight = maxHeigh;
  //       clearInterval(setFlood);
  //     }
  //   }
  // }, 1000 / 30);

  //primitive方式创建.可以制作出水波纹效果
  var setFlood = setInterval(() => {
    if (currentHeight < maxHeigh) {
      currentHeight += speed / 5;
      createPrimitives(adapCoordi, currentHeight, minHeight.value)
      if (currentHeight > maxHeigh) {
        currentHeight = maxHeigh;
        clearInterval(setFlood);
      }
    }
  }, 1000 / 5);
  for (let l of viewer.dataSources._dataSources) {
    if (l.name == "floodRange")
      viewer.dataSources.remove(l)
  }
  viewer.entities.removeAll();
}
//绘制多边形
function draw() {
  var tempPoints = [];
  var handler = new cesium.ScreenSpaceEventHandler(viewer.scene.canvas);

  //左键点击操作
  handler.setInputAction(function (click) {
    //调用获取位置信息的接口
    let position = viewer.scene.pickPosition(click.position);
    tempPoints.push(position);
    let tempLength = tempPoints.length;
    //调用绘制点的接口
    let point = drawPoint(position);
    if (tempLength > 1) {
      let pointline = drawPolyline([tempPoints[tempPoints.length - 2], tempPoints[tempPoints.length - 1]]);
    }
    return;

  }, cesium.ScreenSpaceEventType.LEFT_CLICK);
  //右键点击操作
  handler.setInputAction(function (click) {
    let cartesian = viewer.scene.pickPosition(click.position);
    if (cartesian) {
      let tempLength = tempPoints.length;
      if (tempLength < 3) {
        alert('请选择3个以上的点再执行闭合操作命令');
      } else {
        //闭合最后一条线
        let pointline = drawPolyline([tempPoints[tempPoints.length - 1], tempPoints[0]]);
        drawPolygon(tempPoints);
        adapCoordi = tempPoints;
        // createPolygon(tempPoints);
        handler.destroy();//关闭事件句柄
        handler = null;
      }
    }
  }, cesium.ScreenSpaceEventType.RIGHT_CLICK);
};
function drawPolygon(positions) {
  if (positions.length < 2) return;
  var polygonGeometry = viewer.entities.add({
    name: "面几何对象",
    polygon: {
      // height: 0.1,
      hierarchy: new cesium.PolygonHierarchy(positions),
      material: new cesium.Color.fromCssColorString("#FFD700").withAlpha(0),
      // perPositionHeight: true,
    }
  });
  return polygonGeometry;
};
function drawPolyline(positions) {
  if (positions.length < 1) return;
  var polylineGeometry = viewer.entities.add({
    name: "线几何对象",
    polyline: {
      positions: positions,
      width: 5.0,
      material: new cesium.PolylineGlowMaterialProperty({
        color: cesium.Color.GOLD,
      }),
      depthFailMaterial: new cesium.PolylineGlowMaterialProperty({
        color: cesium.Color.GOLD,
      }),
    }
  });
  return polylineGeometry;
};
function drawPoint(position) {
  var pointGeometry = viewer.entities.add({
    name: "点几何对象",
    position: position,
    point: {
      color: cesium.Color.SKYBLUE,
      pixelSize: 10,
      outlineColor: cesium.Color.YELLOW,
      outlineWidth: 3,
      disableDepthTestDistance: Number.POSITIVE_INFINITY
    }
  });
  return pointGeometry;
};
//创建多边形
function createPrimitives(points, extrudedHeight, minHeight) {
  let waterPrimitive = new cesium.Primitive({
    allowPicking: false,
    asynchronous: false,
    geometryInstances: new cesium.GeometryInstance({
      id: 'floodGeoInstance',
      geometry: new cesium.PolygonGeometry({
        polygonHierarchy: new cesium.PolygonHierarchy(points),
        vertexFormat: cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT,
        extrudedHeight: extrudedHeight,
        height: minHeight,
      }),
    }),
    appearance: new cesium.EllipsoidSurfaceAppearance({
      //当为 true 时，几何体应位于椭圆体的表面上,不是在其上方的恒定高度
      aboveGroud: true,
      material: new cesium.Material({
        fabric: {
          type: 'Water',
          uniforms: {
            blendColor: new cesium.Color(0, 0, 1, 0.3),
            baseWaterColor: cesium.Color.fromAlpha(cesium.Color.fromCssColorString("#538c6e"), 0.7),
            normalMap: "/src/assets/images/map/water.jpg",
            //频率速度设置
            frequency: 20000,
            animationSpeed: 0.02,
            amplitude: 2
          }
        },
      })
    })
  });
  for (let l of viewer.scene.primitives._primitives) {
    if (l._instanceIds == "floodGeoInstance")
      viewer.scene.primitives.remove(l)
  }
  viewer.scene.primitives.add(waterPrimitive);
  // waterPrimitive.update();
  // var sui = waterPrimitive.getGeometryInstanceAttributes('floodGeoInstance');
};
</script>

<style scoped lang="scss">
.dialog_content {
  cursor: default;
}
.header {
  text-align: center;
  position: relative;

  h3 {
    color: #fff;
    line-height: 30px;
  }

  .close {
    position: absolute;
    right: 10px;
    top: -5px;
    font-size: 25px;
    color: #fff;
    cursor: pointer;
  }

  .close:hover {
    color: #ff9a00;
  }
}

.content {
  color: #fff;
  padding: 10px;

  .content-item {
    margin-bottom: 10px;
  }
}
</style>