<template>
  <div class="info-container">
    
    <h3>{{name}}</h3>
    <div id="info-viewer">

    </div>
  </div>
</template>

<script>
export default {
  data(){
    return {
        name:"倾斜模型逻辑单体化"
    }
  },
  methods:{
    initCesium(){
        let box = document.getElementsByClassName("content__default")[0];
        box.style.maxWidth = "100%";
        box.style.paddingTop = 0;

        let Cesium = this.$cesium;
        window.CESIUM_BASE_URL = '/cesium'
        Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5ZjRjNTZkNC01NDYxLTRhMjQtOGEwZC1kZjA3YzQ5YTJlZDkiLCJpZCI6MjYwODQsInNjb3BlcyI6WyJhc3IiLCJnYyJdLCJpYXQiOjE1ODcxOTMwODN9.prGsSKyAW_9Ow5zHYPhbm3LsQL-ApQw5-5PNJkDaHi8";
        var viewer = new Cesium.Viewer("info-viewer", {
            geocoder:false,//位置查找
            homeButton:false,//视图返回初始位置
            sceneModePicker:false,//视角选择器
            baseLayerPicker:false,//底图选择器
            navigationHelpButton:false,//导航帮助按钮
            animation:false,//动画控制器
            creditContainer:document.createElement("div"),//版权显示
            timeline:false,//时间线
            fullscreenButton:true,//全屏控件
            vrButton:false,
            skyBox:false,
            infoBox:false,
            imageryProvider:new Cesium.UrlTemplateImageryProvider({
                url: "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
                minimumLevel: 3,
                maximumLevel: 18
            })
        });
        window.viewer = viewer;
        this._viewer = viewer;
        this.addTiles();
        this.addShp();
        this.initEvent();
    },
    addShp(){
        let url = "/data/dayanta/dayanta.geojson";
        fetch(url).then((res) => res.json()).then((result) => {
            const primitives = new Cesium.PrimitiveCollection({ show:true });
            result.features.forEach((feature) => {
                feature.properties["type"] = "single";
                primitives.add(this.createPrimitiveByFeature1(feature, "rgba(255,255,255,0)"));
            });
            viewer.scene.primitives.add(primitives);// 添加面
        })
    },
    createPrimitiveByFeature1(feature, colorStr) {
        let coords = feature.geometry.coordinates;
        let ground = new Cesium.GroundPrimitive({
            geometryInstances: new Cesium.GeometryInstance({
            geometry: new Cesium.PolygonGeometry({
                polygonHierarchy: coords[0][0][0].length==3?new Cesium.PolygonHierarchy(
                Cesium.Cartesian3.fromDegreesArrayHeights(coords.flat(3))
                ):new Cesium.PolygonHierarchy(
                Cesium.Cartesian3.fromDegreesArray(coords.flat(3))
                ),
            }),
            id: feature.properties,
            attributes: { color:  Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.fromCssColorString(colorStr))},
            }),
            appearance : new Cesium.PerInstanceColorAppearance({
            translucent : false
            })
        });
        return ground;
    },
    addTiles(){
        var tileUrl = "/data/dayanta/tileset.json"
        var tileset = new Cesium.Cesium3DTileset({
            url: tileUrl,
            maximumScreenSpaceError:20,//控制模型的绘制精度，数值越大在同等层级里面加载的模型会越模糊，默认为16

            skipLevelOfDetail: true,
            dynamicScreenSpaceError: true,
            maximumNumberOfLoadedTiles: 10000, //最大加载瓦片个数
            
            dynamicScreenSpaceErrorDensity: 0.00278,
            dynamicScreenSpaceErrorFactor: 4.0,
            dynamicScreenSpaceErrorHeightFalloff: 0.25,
        });
        viewer.scene.primitives.add(tileset);
        viewer.zoomTo(tileset)
        tileset.readyPromise.then((tileset_)=> {
            this.setTilesetHeightAndOffset(tileset_, -420);
        });
    },
    setTilesetHeightAndOffset(tileset, height, x, y) {
        x = x ? x : 0;
        y = y ? y : 0;
        let center;
        if (tileset.boundingSphere) {
            // 3dtiles
            center = tileset.boundingSphere.center;
        } else if (
            tileset._boundingSpheres &&
            tileset._boundingSpheres.length > 0
        ) {
            // Primitive
            center = tileset._boundingSpheres[0].center;
        }
        const cartographic = Cesium.Cartographic.fromCartesian(center);
        const surface = Cesium.Cartesian3.fromRadians(
            cartographic.longitude,
            cartographic.latitude,
            0.0
        );
        const offset = Cesium.Cartesian3.fromRadians(
            cartographic.longitude + x,
            cartographic.latitude + y,
            height
        );
        const translation = Cesium.Cartesian3.subtract(
            offset,
            surface,
            new Cesium.Cartesian3()
        );
        const modelMaxtrix = Cesium.Matrix4.fromTranslation(translation);
        tileset.modelMatrix = modelMaxtrix;
    },
    initEvent(){
        let Cesium = this.$cesium;
        let viewer = this._viewer;
        //添加点击事件
        const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        let vm = this;
        handler.setInputAction(function (movement) {
            //捕获椭球体，将笛卡尔二维平面坐标转为椭球体的笛卡尔三维坐标，返回球体表面的点
            var cartesian3 = viewer.camera.pickEllipsoid(movement.position);
            if (cartesian3) {
                //将笛卡尔三维坐标转为地图坐标（弧度）
                var cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian3);
                //将地图坐标（弧度）转为十进制的度数
                var lat_String = Cesium.Math.toDegrees(cartographic.latitude).toFixed(9);
                var log_String = Cesium.Math.toDegrees(cartographic.longitude).toFixed(9);
                var alti_String = (viewer.camera.positionCartographic.height / 1000).toFixed(2);
                console.log(log_String+","+lat_String);
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        handler.setInputAction(function (movement) {
            //捕获椭球体，将笛卡尔二维平面坐标转为椭球体的笛卡尔三维坐标，返回球体表面的点
            var cartesian3 = viewer.camera.pickEllipsoid(movement.endPosition);
            if (cartesian3) {
                //将笛卡尔三维坐标转为地图坐标（弧度）
                var cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian3);
                //将地图坐标（弧度）转为十进制的度数
                var lat_String = Cesium.Math.toDegrees(cartographic.latitude).toFixed(4);
                var log_String = Cesium.Math.toDegrees(cartographic.longitude).toFixed(4);
                var alti_String = (viewer.camera.positionCartographic.height / 1000).toFixed(2);
                vm.lng = log_String;
                vm.lat = lat_String;
                vm.alti = alti_String;
            }
            // 单体化高亮,清除上一个
            if(window.singlePrimitive){
            // viewer.scene.primitives.remove(window.selectPrimitive);
            // window.selectPrimitive=null;
            let comp = window.singlePrimitive;
            let attr = comp.primitive.getGeometryInstanceAttributes(comp.id);
            attr.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromBytes(255,255,255,0));
            window.singlePrimitive=null;
            }
            let pickPrimitive = viewer.scene.pick(movement.endPosition);
            if(pickPrimitive&&pickPrimitive.id&&pickPrimitive.id.type){
            if(pickPrimitive.id.type == "single"){
                // 设置选中高亮primitive
                var attributes = pickPrimitive.primitive.getGeometryInstanceAttributes(pickPrimitive.id);
                window.singlePrimitive = {
                id:pickPrimitive.id,
                primitive:pickPrimitive.primitive,
                }
                attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromBytes(0,255,0,150));
            }
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    },
  
  },
  mounted(){
    this.initCesium()
  }
}
</script>

<style lang='stylus' scoped>
#info-viewer{
  height: 80vh;
  width: 100%
}
</style>