<template>
    <!-- <style>
        /* @import url(../templates/bucket.css); */
    </style> -->
    <!-- <qq class="qq"/> -->
    <div id="cesiumContainer" class="all">
        <div id="toolbar"></div>
    </div>
    <div class="qq">
        <el-select v-model="value" transfer="false" placeholder="line" style="width: 120px" @change="change"
            filterable="true" allow-create="true">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-text class="mx-1" size="large">{{ output }}</el-text>
    </div>
    <div class="input">
        <el-input v-model="input" style="width: 240px" placeholder="示例：8000，8000，8000" />
        <el-button>输入</el-button>
    </div>

</template>

<script setup lang="ts">
import { onMounted } from 'vue'
import * as Cesium from 'cesium'



import { ref } from 'vue'
let output = []
const input = ref('')
let activeShapePoints = [];


let drawingMode = 'line';
const change = () => {
    drawingMode = value.value
}
const value = ref('')
const options = [
    {
        value: 'line',
        label: 'line',
    },
    {
        value: 'polygon',
        label: 'polygon',
    },
    {
        value: 'sector',
        label: 'sector',
    },
    {
        value: 'ellipse',
        label: 'ellipse',
    }
]

onMounted(() => {
    Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIyYTI3MDQxMS1hYzgxLTRlYTQtODExZS00YzdmYjM0YTg3OTAiLCJpZCI6MjI0NzQzLCJpYXQiOjE3MTkzOTcxMDF9._VD-W1rEy7jSUtPmcVytEYbZIZ00_IeHCZm59Kua5aE'
    const viewer = new Cesium.Viewer("cesiumContainer", {
        selectionIndicator: false,
        infoBox: false,
        // terrain: Cesium.Terrain.fromWorldTerrain(),
        // terrainProvider:Cesium.createWorldTerrain(),
    });

    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
    );
    function createPoint(worldPosition) {
        const point = viewer.entities.add({
            position: worldPosition,
            point: {
                color: Cesium.Color.WHITE,
                pixelSize: 5,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            },
        });
        return point;
    }
    drawingMode = "line";

    function drawShape(positionData) {
        let shape;
        if (drawingMode === "line") {
            shape = viewer.entities.add({
                polyline: {
                    positions: positionData,
                    clampToGround: true,
                    width: 3,
                },
            });
        } else if (drawingMode === "polygon") {
            shape = viewer.entities.add({
                polygon: {
                    hierarchy: positionData,
                    material: new Cesium.ColorMaterialProperty(
                        Cesium.Color.WHITE.withAlpha(0.7)
                    ),
                },
            });
        } else if (drawingMode === "sector") {
            let angleone = computerJiao(positionData[0], positionData[1])
            let angletwo = computerJiao(positionData[0], positionData[2])
            let r = computerR(positionData[0], positionData[1])

            shape = viewer.entities.add({
                position: positionData[0],
                ellipsoid: {
                    radii: new Cesium.Cartesian3(r, r, 1.0),
                    minimumClock: Cesium.Math.toRadians(angleone),
                    maximumClock: Cesium.Math.toRadians(angletwo),
                    material: Cesium.Color.DARKCYAN.withAlpha(0.3),
                    outline: false,
                },
            });
        }
        else if (drawingMode === "ellipse") {
            let r = computerR(positionData[0], positionData[1])
            shape = viewer.entities.add({
                position: positionData[0],
                ellipse: {
                    semiMajorAxis: r,
                    semiMinorAxis: r,
                    material: Cesium.Color.WHITE,
                    fill: true,
                    outline: false,
                    height: 20000,
                    outerWidth: 10000,
                    extrudedHeight: 200000.0,
                    rotation: 0.78539,
                },
            });
        }
        return shape;
    }
    activeShapePoints = [];
    let activeShape;
    let floatingPoint;
    const handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
    handler.setInputAction(function (event) {
        const ray = viewer.camera.getPickRay(event.position);
        const earthPosition = viewer.scene.globe.pick(ray, viewer.scene);
        if (Cesium.defined(earthPosition)) {
            if (activeShapePoints.length === 0) {
                floatingPoint = createPoint(earthPosition);
                activeShapePoints.push(earthPosition);
                const dynamicPositions = new Cesium.CallbackProperty(function () {
                    if (drawingMode === "polygon") {
                        return new Cesium.PolygonHierarchy(activeShapePoints);
                    }
                    return activeShapePoints;
                }, false);
                console.log(activeShapePoints[0])

                activeShape = drawShape(dynamicPositions);
            }
            activeShapePoints.push(earthPosition);
            createPoint(earthPosition);
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    handler.setInputAction(function (event) {
        if (Cesium.defined(floatingPoint)) {
            const ray = viewer.camera.getPickRay(event.endPosition);
            const newPosition = viewer.scene.globe.pick(ray, viewer.scene);
            if (Cesium.defined(newPosition)) {
                floatingPoint.position.setValue(newPosition);
                activeShapePoints.pop();
                activeShapePoints.push(newPosition);
            }
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    // Redraw the shape so it's not dynamic and remove the dynamic shape.
    function terminateShape() {
        activeShapePoints.pop();
        drawShape(activeShapePoints);
        viewer.entities.remove(floatingPoint);
        viewer.entities.remove(activeShape);
        floatingPoint = undefined;
        activeShape = undefined;
        activeShapePoints = [];
    }
    handler.setInputAction(function (event) {
        terminateShape();
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    function computerR(point_one, point_two) {

        let r = Math.sqrt((point_one.x - point_two.x) ** 2 + (point_one.y - point_two.y) ** 2 + (point_one.z - point_two.z) ** 2)

        return r
    }
    function computerJiao(point_one, point_two) {
        let one = Cesium.Cartographic.fromCartesian(point_one)
        let two = Cesium.Cartographic.fromCartesian(point_two)
        let onelon = Cesium.Math.toDegrees(one.longitude)
        let onelat = Cesium.Math.toDegrees(one.latitude)
        let twolon = Cesium.Math.toDegrees(two.longitude)
        let twolat = Cesium.Math.toDegrees(two.latitude)
        let r = Math.sqrt((twolat - onelat) ** 2 + (twolon - onelon) ** 2)
        let jiaorad = Math.asin(((twolon) - (onelon)) / r)
        let jiao = jiaorad * (180 / Math.PI)
        if ((twolat > onelat) && (twolon > onelon)) { jiao = jiao }
        else if ((twolon < onelon) && (twolat > onelat)) { jiao = 180 - jiao }
        else if ((twolon < onelon) && (twolat < onelat)) { jiao = jiao + 180 }
        else if ((twolon > onelon) && (twolat < onelat)) { jiao = 360 - jiao }

        return jiao
    }



    // Zoom in to an area with mountains
    // viewer.camera.lookAt(
    //     Cesium.Cartesian3.fromDegrees(-122.2058, 46.1955, 1000.0),
    //     new Cesium.Cartesian3(5000.0, 5000.0, 5000.0)
    // );
    // viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
    //     function setHandler() {
    //         const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    //         // 注册鼠标按下事件
    //         handler.setInputAction((e) => {
    //             const pick = viewer.scene.pick(e.position);
    //             if (!Cesium.defined(pick)) { return; };// 如果点击空白区域，则不往下执行
    //             viewer.scene.screenSpaceCameraController.enableRotate = false;// 将相机锁定，不然后续移动实体时相机也会动
    //             pick.id.model.color = Cesium.Color.fromAlpha(Cesium.Color.RED, 1)  //设置颜色

    //             // 注册鼠标拖拽事件
    //             viewer.screenSpaceEventHandler.setInputAction((arg) => {// 为viewer绑定MOUSE_MOVE事件监听器（执行函数，监听的事件）
    //                 const position = arg.endPosition;// arg有startPosition与endPosition两个属性，即移动前后的位置信息：Cartesian2对象
    //                 const cartesian = viewer.scene.globe.pick(viewer.camera.getPickRay(position), viewer.scene);//将Cartesian2转为Cartesian3
    //                 pick.id.position._value = cartesian
    //             }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);


    //             // 绑定鼠标抬起事件
    //             viewer.screenSpaceEventHandler.setInputAction(({ position }) => {//为viewer绑定LEFT_UP事件监听器（执行函数，监听的事件）
    //                 viewer.scene.screenSpaceCameraController.enableRotate = true;// 取消相机锁定
    //                 pick.id.model.color = null  //设置颜色
    //                 viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);// 解除viewer的MOUSE_MOVE事件监听器
    //             }, Cesium.ScreenSpaceEventType.LEFT_UP)

    //         }, Cesium.ScreenSpaceEventType.LEFT_DOWN);}

})



</script>



<style>
.all {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    border: none;
    width: 100%;
    height: 100%
}

.cesium-viewer-bottom {
    display: none;
}

.qq {
    position: absolute;
    top: 50px;
    left: 50px;
    z-index: 99999999;
}

.input {
    position: absolute;
    top: 50px;
    left: 200px;
}
</style>
