<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" justify="center">
        <!-- <a-button @click="draw()">绘制图形</a-button>
        <a-button @click="clean()">清除图形</a-button>
        <a-button @click="startPath()">{{ startBtn }}</a-button>
        <a-button @click="endRoaming">取消漫游</a-button> -->
        <el-button @click="draw()" size="small">新增路线</el-button>
        <a-upload :accept="acceptType" :showUploadList="false" :customRequest="customUpload">
          <a-button size="small" style="margin-left: 15px;">
            导入
          </a-button>
        </a-upload>
        <a-button size="small" style="margin-left: 15px;" @click="exportKml">
          导出
        </a-button>
        <!-- <el-button icon="Delete" @click="clean()" size="small"></el-button> -->
      </el-row>
      <el-row class="path-table">
        <table width="100%" class="table-wrapper">
          <thead>
            <tr>
              <td>&nbsp;&nbsp;</td>
              <td class="table-name">名称</td>
              <td class="table-tool">操作</td>
            </tr>
          </thead>
          <tbody class="table-body">
            <tr v-for="item in options.roamingList">
              <td><el-checkbox v-model="checked" size="small" /></td>
              <td>{{ item.id }}</td>
              <td>
                <el-button size="large" class="button-link" :icon="item.playIcon" link
                  @click="startPath(item)"></el-button>
                <!-- <el-button size="large" class="button-link" icon="Edit" link></el-button> -->
                <el-button size="large" class="button-link" icon="Position" link
                  @click="positionEntity(item)"></el-button>
                <el-button size="large" class="button-link" icon="Delete" link @click="removeRoaming(item)"></el-button>
                <el-progress type="dashboard" :format="speedShow" :percentage="percentage" :color="colors" :width="20" />
                <el-slider v-model="percentage" vertical height="20px" @change="speedChange(item)" input-size="large"
                  :format-tooltip="speedController" />
                <el-slider v-model="alt" vertical height="20px" @change="heightChange(item)" input-size="large"
                  :format-tooltip="altitudeController" />
              </td>
            </tr>
          </tbody>

        </table>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, getCurrentInstance, toRaw } from 'vue';
import shp from 'shpjs/dist/shp';
import useMapStore from '@/store/modules/maps';
import Roaming from './Roamimg.js';
import { ro } from 'element-plus/es/locale';
const props = defineProps(['terrain']);
let viewer = useMapStore().$state.viewer;
let cesium = useMapStore().$state.cesium;
const acceptType = ref(".zip,.kml,.geojson,.json");
const labelEntity = ref(null);
const pointEntity = ref([]);
const roaming = ref(null);
const checked = ref(true);
const playIcon = ref("VideoPlay")
const startBtn = ref("开始漫游");
const percentage = ref(6)
const alt = ref(10)
const colors = [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#5cb87a', percentage: 60 },
  { color: '#1989fa', percentage: 80 },
  { color: '#6f7ad3', percentage: 100 },
]
const options = reactive({
  id: 0,
  roamingList: [],
  lastRoaming: null
})
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 = "route";
      for (let entity of geojson.entities.values) {
        if (entity.polyline != undefined) {
          pointEntity.value = entity.polyline.positions.getValue();
          break;
        }
      }
      for (let l of viewer.dataSources._dataSources) {
        if (l.name == "route")
          viewer.dataSources.remove(l)
      }
      viewer.entities.removeAll();
      roaming.value = new Roaming(viewer, {
        id: '路径' + options.id,
        modeluri: 'src/assets/models/car.glb',
        time: 360,
        Lines: pointEntity.value,
        isPathShow: false
      })
      if (options.lastRoaming == null) {
        options.lastRoaming = roaming.value;
      } else {
        viewer.entities.remove(options.lastRoaming.entity);
        options.lastRoaming = roaming.value;
      }
      options.id = options.id + 1;
      roaming.value.playIcon = 'VideoPlay';
      options.roamingList.push(roaming.value);
    });
  }
  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 = "route";
      for (let entity of kml.entities.values) {
        if (entity.polyline != undefined) {
          pointEntity.value = entity.polyline.positions.getValue();
          break;
        }
      }
      for (let l of viewer.dataSources._dataSources) {
        if (l.name == "route")
          viewer.dataSources.remove(l)
      }
      viewer.entities.removeAll();
      roaming.value = new Roaming(viewer, {
        id: '路径' + options.id,
        modeluri: 'src/assets/models/car.glb',
        time: 600,
        Lines: pointEntity.value,
        isPathShow: checked.value
      })
      if (options.lastRoaming == null) {
        options.lastRoaming = roaming.value;
      } else {
        viewer.entities.remove(options.lastRoaming.entity);
        options.lastRoaming = roaming.value;
      }
      options.id = options.id + 1;
      roaming.value.playIcon = 'VideoPlay';
      options.roamingList.push(roaming.value);
    });
  }
  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 = "route";
          for (let entity of geojson.entities.values) {
            if (entity.polyline != undefined) {
              pointEntity.value = entity.polyline.positions.getValue();
              break;
            }
          }
          for (let l of viewer.dataSources._dataSources) {
            if (l.name == "route")
              viewer.dataSources.remove(l)
          }
          viewer.entities.removeAll();
          roaming.value = new Roaming(viewer, {
            id: '路径' + options.id,
            modeluri: 'src/assets/models/car.glb',
            time: 360,
            Lines: pointEntity.value,
            isPathShow: false
          })
          if (options.lastRoaming == null) {
            options.lastRoaming = roaming.value;
          } else {
            viewer.entities.remove(options.lastRoaming.entity);
            options.lastRoaming = roaming.value;
          }
          options.id = options.id + 1;
          roaming.value.playIcon = 'VideoPlay';
          options.roamingList.push(roaming.value);
        });
      });
    }
  }
};
//绘制多边形
function draw() {
  let tempPoints = [];
  let handler = new cesium.ScreenSpaceEventHandler(viewer.scene.canvas);

  //左键点击操作
  handler.setInputAction(function (click) {
    let position;
    const pick = viewer.scene.pick(click.position);
    //调用获取位置信息的接口
    if (cesium.defined(pick)) {
      if (pick.primitive) {
        let ellipsoid = viewer.scene.globe.ellipsoid;
        let cartographic = ellipsoid.cartesianToCartographic(viewer.scene.pickPosition(click.position));
        let longtitude = cesium.Math.toDegrees(cartographic.longitude);
        let latitude = cesium.Math.toDegrees(cartographic.latitude);
        let height = cartographic.height;
        position = cesium.Cartesian3.fromDegrees(longtitude, latitude, height + 0.1);
      } else {
        if (props.terrain) {
          position = viewer.scene.pickPosition(click.position);
        } else {
          position = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid);
        }
      }
    } else {
      if (props.terrain) {
        position = viewer.scene.pickPosition(click.position);
      } else {
        position = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid);
      }
    }

    tempPoints.push(position);
    pointEntity.value = tempPoints;
    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 (move) {
    let position;
    if (props.terrain) {
      position = viewer.scene.pickPosition(move.endPosition);
    } else {
      position = viewer.camera.pickEllipsoid(move.endPosition, viewer.scene.globe.ellipsoid);
    }
    if (cesium.defined(labelEntity.value)) {
      labelEntity.value.position = position
    } else {
      drawLabel(position);
    }
  }, cesium.ScreenSpaceEventType.MOUSE_MOVE)

  //右键结束操作
  handler.setInputAction(function (click) {
    viewer.entities.removeAll();
    roaming.value = new Roaming(viewer, {
      id: '路径' + options.id,
      modeluri: 'src/assets/models/car.glb',
      time: 200,
      Lines: pointEntity.value,
      isPathShow: false
    })
    if (options.lastRoaming == null) {
      options.lastRoaming = roaming.value;
    } else {
      viewer.entities.remove(options.lastRoaming.entity);
      options.lastRoaming = roaming.value;
    }
    options.id = options.id + 1;
    roaming.value.playIcon = 'VideoPlay';
    options.roamingList.push(roaming.value);
    tempPoints = [];
    handler.destroy();//关闭事件句柄
    handler = null;
    labelEntity.value = null;
  }, cesium.ScreenSpaceEventType.RIGHT_CLICK);
};

// 绘制线对象
function drawPolyline(positions) {
  if (positions.length < 1) return;
  let 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,
      }),
      clampToGround: true //贴地
    }
  });
  return polylineGeometry;
};

// 绘制点对象
function drawPoint(position) {
  let pointGeometry = viewer.entities.add({
    name: "点几何对象",
    position: position,
    point: {
      color: cesium.Color.SKYBLUE,
      pixelSize: 10,
      outlineColor: cesium.Color.YELLOW,
      outlineWidth: 3,
      // heightReference: cesium.HeightReference.CLAMP_TO_GROUND,
      disableDepthTestDistance: Number.POSITIVE_INFINITY
    }
  });
  return pointGeometry;
};

// 绘制提示label
function drawLabel(position) {
  let labelGeometry = new cesium.Entity({
    name: "提示label",
    label: {
      text: "左键可继续绘制，右键结束绘制",
      showBackground: true,
      font: '14px monospace',
      fillColor: new cesium.Color(255, 255, 255, 1),
      backgroundPadding: new cesium.Cartesian2(10, 10),
      pixelOffset: new cesium.Cartesian2(80, 30),
      backgroundColor: new cesium.Color(0.165, 0.165, 0.165, 0.9),
      horizontalOrigin: cesium.HorizontalOrigin.CENTER,
      verticalOrigin: cesium.VerticalOrigin.TOP
    }
  });

  labelGeometry.position = position,
    labelEntity.value = labelGeometry
  viewer.entities.add(labelEntity.value);
  return labelGeometry;
}

// 开始漫游
function startPath(roaming) {
  viewer.entities.removeAll();
  viewer.clock.currentTime = roaming.start;
  viewer.entities.add(roaming.entity);
  if (roaming) {
    if (roaming.playIcon == 'VideoPlay') {
      roaming.PauseOrContinue(true, 0);
      roaming.setRoamingModelVisibility(checked.value)
      roaming.setRoamingPathVisibility(checked.value)

      roaming.playIcon = 'VideoPause'
    } else {
      roaming.PauseOrContinue(false, 0);
      roaming.playIcon = 'VideoPlay'
    }
  }
}

function speedChange(roaming) {
  roaming.ChangeRoamingSpeed(percentage.value / 10)
}
function heightChange(roaming) {
  if (roaming) {
    if (roaming.playIcon == 'VideoPlay') {
      roaming.PauseOrContinue(true, alt.value * 10 + 3000);
      roaming.setRoamingModelVisibility(checked.value)
      roaming.setRoamingPathVisibility(checked.value)
      roaming.playIcon = 'VideoPause'
    } else {
      roaming.PauseOrContinue(false, 0);
      roaming.playIcon = 'VideoPlay'
    }
  }
}
// 定位到路线
function positionEntity(roaming) {

  viewer.flyTo(toRaw(roaming.entity));
}

function removeRoaming(roaming) {
  roaming.EndRoaming();
  options.roamingList = options.roamingList.filter(item => item.id != roaming.id);
}

function exportKml() {
  if (viewer.entities.values.length != 0) {
    let entityCollection = new cesium.EntityCollection();
    for (let v of viewer.entities.values) {
      entityCollection.add(v.polyline)
    }
    cesium.exportKml({
      entities: viewer.entities,
      modelCallback: modelCallback,
    }).then(res => {
      console.log(typeof res.kml);
      const blobFile = new Blob([res.kml]);
      downloadBlob("路径.kml", blobFile)
    })
  }
}

function downloadBlob(filename, blob) {
  const elem = window.document.createElement("a");
  elem.href = window.URL.createObjectURL(blob);
  elem.download = filename;
  document.body.appendChild(elem);
  elem.click();
  document.body.removeChild(elem);

}

function modelCallback(modelGraphics, time, externalFiles) {
  const resource = modelGraphics.uri.getValue(time);
  return "";
}

function speedShow() {
  return percentage.value;
}

function speedController() {
  return "时速" + percentage.value + "km";
}

function altitudeController() {
  return "海拔:" + (alt.value * 10 + 3000) + "m";
}
</script>

<style scoped lang="scss">
:deep(.el-progress) {
  left: 10px;
  top: 10px;
}

:deep(.el-progress__text) {
  font-weight: bolder;
  font-size: 10px;
  color: #00ff15;
  margin-left: -15px;
  line-height: 1;
}

:deep(.el-slider) {
  top: 8px;
  --el-slider-button-size: 10px;
}

.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;
  }
}

.path-table {
  width: 94%;
  min-height: 100px;
  max-height: 200px;
  margin: 0 auto;
  border: 1px solid #fff;
  overflow-y: scroll;

  .table-wrapper {
    text-align: center;
    color: #fff;

  }

  .table-name {
    width: 30%;
  }

  .table-tool {
    width: 70%;
  }

  .table-wrapper td {
    line-height: 30px;
  }

  .button-link {
    color: #fff;
    font-size: 18px;
    cursor: pointer;
  }

  .button-link:hover {
    color: #fffb00;
  }
}</style>