import configValue from "../config/config.js";
import { getProductValue } from "@/api/lang/pendingOrder";
class otgCesiumUtils {
    //初始化地图
    static initCesium(divMapId) {
        let Cesium = window.Cesium;
        this.Cesium = Cesium;
        let options = {
            selectionIndicator: false,
            homeButton: false, //主页按钮，默认true
            // scene3DOnly: true, // 每个几何实例仅以3D渲染以节省GPU内存
            animation: false, //动画控制，默认true
            baseLayerPicker: false, //是否显示图层选择控件
            geocoder: false, //地名查找,默认true
            timeline: false, //时间线,默认true
            navigationHelpButton: false, //导航帮助说明,默认true
            sceneModePicker: false, //是否显示投影方式控件
            infoBox: false, //点击要素之后显示的信息,默认true
            fullscreenButton: false, //全屏按钮,默认显示true
            navigationInstructionsInitiallyVisible: false,
            mapMode2D: Cesium.MapMode2D.INFINITE_SCROLL,
            imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
                url:
                    "https://{s}.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=d7648495378ad7ebe74327207dfc09a8",
                layer: "tdtBasicLayer",
                style: "default",
                maximumLevel: 18,
                format: "image/jpeg",
                tileMatrixSetID: "GoogleMapsCompatible",
                show: true,
                subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"]
            }),
            // html2canvas截图场景黑屏解决
            contextOptions: {
                webgl: {
                    alpha: true,
                    depth: true,
                    stencil: true,
                    antialias: true,
                    premultipliedAlpha: true,
                    //通过canvas.toDataURL()实现截图需要将该项设置为true
                    preserveDrawingBuffer: true,
                    failIfMajorPerformanceCaveat: true
                }
            }
        };
        let farViewer = new Cesium.Viewer(divMapId[0], options);
        let nearViewer = new Cesium.Viewer(divMapId[1], options);
        window.selfDefine.farViewer = farViewer;
        window.selfDefine.nearViewer = nearViewer;
        this.farViewer = farViewer;
        this.nearViewer = nearViewer;

        farViewer.scene.globe.depthTestAgainstTerrain = false;
        nearViewer.scene.globe.depthTestAgainstTerrain = false;
    }

    //添加wms
    static addlayer(geoWorkspace, layerName) {
        // let privide2 = new Cesium.WebMapServiceImageryProvider({
        //     url: "http://127.0.0.1:8087/geoserver/microwave/wms", //服务地址
        //     layers: geoWorkspace+':'+layerName, //服务图层，需要修改成你自己发布的名称
        //     parameters: {
        //       service: "WMS",
        //       format: "image/png",
        //       transparent: true
        //     }
        //   });
        // let layer2= new this.Cesium.ImageryLayer(privide2)
        // this.privide2=layer2
        let privide1 = this.creatTwoViewerLayer(geoWorkspace, layerName);
        let layer1 = new Cesium.ImageryLayer(privide1);
        let privide2 = this.creatTwoViewerLayer(geoWorkspace, layerName);
        let layer2 = new Cesium.ImageryLayer(privide2);
        this.nearViewer.imageryLayers.add(layer1);
        this.farViewer.imageryLayers.add(layer2);
    }
    //切换添加产品展示图层
    static addFarlayer(geoWorkspace, layerName) {
        let privide2 = this.creatTwoViewerLayer(geoWorkspace, layerName);
        let layer2 = new Cesium.ImageryLayer(privide2);
        this.farViewer.imageryLayers.add(layer2);
    }
    //切换添加局部放大图图层
    static addNearlayer(geoWorkspace, layerName) {
        let privide1 = this.creatTwoViewerLayer(geoWorkspace, layerName);
        let layer1 = new Cesium.ImageryLayer(privide1);
        this.nearViewer.imageryLayers.add(layer1);
    }

    static creatTwoViewerLayer(geoWorkspace, layerName) {
        let matrixIds = [
            "EPSG:4326:0",
            "EPSG:4326:1",
            "EPSG:4326:2",
            "EPSG:4326:3",
            "EPSG:4326:4",
            "EPSG:4326:5",
            "EPSG:4326:6",
            "EPSG:4326:7",
            "EPSG:4326:8",
            "EPSG:4326:9",
            "EPSG:4326:10",
            "EPSG:4326:11",
            "EPSG:4326:12",
            "EPSG:4326:13",
            "EPSG:4326:14",
            "EPSG:4326:15",
            "EPSG:4326:16",
            "EPSG:4326:17",
            "EPSG:4326:18",
            "EPSG:4326:19",
            "EPSG:4326:20",
            "EPSG:4326:21"
        ];
        return new Cesium.WebMapTileServiceImageryProvider({
            url: configValue.urlprefix.otgGeoServerUrl,
            // url: 'http://39.105.100.186:8087/geoserver/gwc/service/wmts',
            layer: geoWorkspace + ":" + layerName,
            style: "",
            format: "image/png",
            tileMatrixSetID: "EPSG:4326",
            tileMatrixLabels: matrixIds,
            tilingScheme: new Cesium.GeographicTilingScheme({
                numberOfLevelZeroTilesX: 2,
                numberOfLevelZeroTilesY: 1
            })
        });
    }
    // 定位到tif影像处
    static flyToLayer(cLon, cLat) {
        this.farViewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(cLon, cLat, 50000.0)
        });
        this.nearViewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(cLon, cLat, 30000.0)
        });
    }
    //删除wms
    static closelayer() {
        //wms服务
        this.farViewer.imageryLayers.remove(this.privide);
        this.nearViewer.imageryLayers.remove(this.privide);
    }
    static clearFarLayers() {
        for (var i = this.farViewer.imageryLayers.length - 1; i >= 0; --i) {
            if (!this.farViewer.imageryLayers.get(i).isBaseLayer()) {
                this.farViewer.imageryLayers.remove(this.farViewer.imageryLayers.get(i));
            }
        }
    }
    static clearNearLayers() {
        for (var i = this.nearViewer.imageryLayers.length - 1; i >= 0; --i) {
            if (!this.nearViewer.imageryLayers.get(i).isBaseLayer()) {
                this.nearViewer.imageryLayers.remove(this.nearViewer.imageryLayers.get(i));
            }
        }
    }
    static addPointToViewer(pLon, pLat, pAlt) {
        this.farViewer.entities.add({
            position: Cesium.Cartesian3.fromDegrees(pLon, pLat, pAlt),
            point: {
                pixelSize: 10,
                color: Cesium.Color.YELLOW
            }
        });
    }
    static addPointToFarViewer(pLon, pLat, pAlt) {
        var peOfFarViewer = this.farViewer.entities.add({
            position: Cesium.Cartesian3.fromDegrees(pLon, pLat, pAlt),
            point: {
                pixelSize: 10,
                color: Cesium.Color.YELLOW
            }
        });
        this.farViewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(pLon, pLat, 5000)
        });
    }
    static addPointToNearViewer(pLon, pLat, pAlt) {
        var peOfNearViewer = this.nearViewer.entities.add({
            position: Cesium.Cartesian3.fromDegrees(pLon, pLat, pAlt),
            point: {
                pixelSize: 10,
                color: Cesium.Color.YELLOW
            }
        });
        this.nearViewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(pLon, pLat, 1000)
        });
    }

    static removePoint() {
        this.farViewer.entities.removeAll();
        this.nearViewer.entities.removeAll();
    }
    static drawPoint(callback) {
        let self = this;
        //坐标存储
        // let positions,newPoi;
        this.handler = new Cesium.ScreenSpaceEventHandler(self.nearViewer.scene.canvas);
        let ellipsoid = self.nearViewer.scene.globe.ellipsoid;
        //单击鼠标左键画点
        this.handler.setInputAction(function (movement) {
            let cartesian = self.nearViewer.scene.camera.pickEllipsoid(
                movement.position,
                self.nearViewer.scene.globe.ellipsoid
            );
            let c = ellipsoid.cartesianToCartographic(cartesian);
            let spLon = Cesium.Math.toDegrees(c.longitude).toFixed(8);
            let spLat = Cesium.Math.toDegrees(c.latitude).toFixed(8);
            let spAlt = c.height.toFixed(2);
            const positions = [spLon, spLat, spAlt];
            self.nearViewer.entities.removeById("theSamePoint");
            const newPoi = self.nearViewer.entities.add({
                id: "theSamePoint",
                position: cartesian,
                point: {
                    color: Cesium.Color.RED,
                    pixelSize: 10
                    // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
                }
            });
            callback(positions);
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
    static stopDrowPoi() {
        this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
    //Far viewer 鼠标点击
    static handleClickFar() {
        var scene = this.farViewer.scene;
        var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
        const that = this;
        handler.setInputAction(function onLeftClick(movement) {
            //清除历史单击点
            handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
            var cartesian = that.farViewer.camera.pickEllipsoid(
                movement.position,
                scene.globe.ellipsoid
            );
            if (cartesian) {
                var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
                var longitudeString = Cesium.Math.toDegrees(cartographic.longitude).toFixed(6);
                var latitudeString = Cesium.Math.toDegrees(cartographic.latitude).toFixed(6);
            }
            //取回像元值
            let pValue = 0;
            that.farViewer.dataSources.removeAll();
            const dataSource = new Cesium.CustomDataSource("textPoint");
            // const of = new FormData();
            // of.append("dataPath", sessionStorage.getItem("tifPath"));
            // of.append("lon", longitudeString);
            // of.append("lat", latitudeString);
            const of = {
                angleDataIds: [],
                geoX: longitudeString,
                geoY: latitudeString,
                metaDataId: sessionStorage.getItem('metaDataId'),
                referImageIds: []
            }
            getProductValue(of).then(res => {
                if (res.code == 200) pValue = res.data.imagePixel;
                dataSource.entities.add({
                    position: new Cesium.Cartesian3.fromDegrees(
                        Number(longitudeString),
                        Number(latitudeString),
                        50
                    ),
                    label: {
                        text: "像素值:" + pValue,
                        font: "20px sans-serif",
                        showBackground: true,
                        eyeOffset: new Cesium.Cartesian3(0, 3.5, 0),
                        fillColor: Cesium.Color.BLACK, //字体颜色
                        backgroundColor: Cesium.Color.WHITE, //背景颜色
                        style: Cesium.LabelStyle.FILL, //label样式
                        outlineWidth: 2,
                        verticalOrigin: Cesium.VerticalOrigin.CENTER, //垂直位置
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER, //水平位置
                        pixelOffset: new Cesium.Cartesian2(0, -20) //偏移
                    }
                });
                that.farViewer.dataSources.add(dataSource);
            });
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
    //Near viewer 鼠标点击
    static handleClickNear() {
        var scene = this.nearViewer.scene;
        var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
        const that = this;
        handler.setInputAction(function onLeftClick(movement) {
            //清除历史单击点
            handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
            var cartesian = that.nearViewer.camera.pickEllipsoid(
                movement.position,
                scene.globe.ellipsoid
            );
            if (cartesian) {
                var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
                var longitudeString = Cesium.Math.toDegrees(cartographic.longitude).toFixed(6);
                var latitudeString = Cesium.Math.toDegrees(cartographic.latitude).toFixed(6);
            }
            //取回像元值
            let pValue = 0;
            that.nearViewer.dataSources.removeAll();
            const dataSource = new Cesium.CustomDataSource("textPoint");
            // const of = new FormData();
            // of.append("dataPath", sessionStorage.getItem("tifPath"));
            // of.append("lon", longitudeString);
            // of.append("lat", latitudeString);
            const of = {
                angleDataIds: [],
                geoX: longitudeString,
                geoY: latitudeString,
                metaDataId: sessionStorage.getItem('metaDataId'),
                referImageIds: []
            }
            getProductValue(of).then(res => {
                if (res.code == 200) pValue = res.data.imagePixel;
                dataSource.entities.add({
                    position: new Cesium.Cartesian3.fromDegrees(
                        Number(longitudeString),
                        Number(latitudeString),
                        50
                    ),
                    label: {
                        text: "像素值:" + pValue,
                        font: "20px sans-serif",
                        showBackground: true,
                        eyeOffset: new Cesium.Cartesian3(0, 3.5, 0),
                        fillColor: Cesium.Color.BLACK, //字体颜色
                        backgroundColor: Cesium.Color.WHITE, //背景颜色
                        style: Cesium.LabelStyle.FILL, //label样式
                        outlineWidth: 2,
                        verticalOrigin: Cesium.VerticalOrigin.CENTER, //垂直位置
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER, //水平位置
                        pixelOffset: new Cesium.Cartesian2(0, -20) //偏移
                    }
                });
                that.nearViewer.dataSources.add(dataSource);
            });
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
}

export default otgCesiumUtils;
