import CesiumNavigation from "cesium-navigation-es6";
import configValue from "../config/config.js";
import { getProductValue } from "@/api/lang/pendingOrder";

const iconClose = require("@/assets/images/close.png");

class CesiumUtils {
    //初始化地图
    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
            // sceneMode:Cesium.SceneMode.SCENE2D,
            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 viewer = new Cesium.Viewer(divMapId, options);
        window.selfDefine.viewer = viewer;
        this.viewer = viewer;
        viewer.scene.globe.depthTestAgainstTerrain = false;
        viewer.camera.setView({
            destination: Cesium.Cartesian3.fromDegrees(105.973421, 38.757527, 7000000.0),
            duration: 4
        });
        var optionsNav = {};
        // 用于在使用重置导航重置地图视图时设置默认视图控制。接受的值是Cesium.Cartographic 和 Cesium.Rectangle.
        optionsNav.defaultResetView = new Cesium.Cartographic.fromDegrees(
            105.973421,
            38.757527,
            7000000
        );
        // 用于启用或禁用罗盘。true是启用罗盘，false是禁用罗盘。默认值为true。如果将选项设置为false，则罗盘将不会添加到地图中。
        optionsNav.enableCompass = true;
        // 用于启用或禁用缩放控件。true是启用，false是禁用。默认值为true。如果将选项设置为false，则缩放控件将不会添加到地图中。
        optionsNav.enableZoomControls = true;
        // 用于启用或禁用距离图例。true是启用，false是禁用。默认值为true。如果将选项设置为false，距离图例将不会添加到地图中。
        optionsNav.enableDistanceLegend = true;
        // 用于启用或禁用指南针外环。true是启用，false是禁用。默认值为true。如果将选项设置为false，则该环将可见但无效。
        optionsNav.enableCompassOuterRing = false;
        // console.log('CesiumNavigation:', CesiumNavigation);
        CesiumNavigation(viewer, optionsNav);
    }

    //添加wms
    static addlayer(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"
        ];
        let privide = new Cesium.WebMapTileServiceImageryProvider({
            url: configValue.urlprefix.geoserverUrl,
            // 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
            })
        });
        let layer1 = new this.Cesium.ImageryLayer(privide);
        this.privide = layer1;
        //wms服务
        this.viewer.imageryLayers.add(layer1);
        // this.viewer.camera.flyTo({
        //     destination: Cesium.Cartesian3.fromDegrees(113.3706577887299, 22.99824617654343, 300000.0)
        // });
    }

    // 定位到tif影像处
    static flyToLayer(cLon, cLat) {
        this.viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(cLon, cLat, 30000)
        });
    }

    static flyToLayerRect(minLon, minLat, maxLon, maxLat) {
        minLon = Number(minLon);
        minLat = Number(minLat);
        maxLon = Number(maxLon);
        maxLat = Number(maxLat);
        const ctLon = ((minLon + maxLon) / 2).toFixed(8);
        const ctLat = ((minLat + maxLat) / 2).toFixed(8);
        const west = minLon * 2 - ctLon;
        const south = minLat * 2 - ctLat;
        const east = maxLon * 2 - ctLon;
        const north = maxLat * 2 - ctLat;
        const rectangle = Cesium.Rectangle.fromDegrees(west, south, east, north);
        this.viewer.camera.flyTo({
            destination: rectangle
        });
    }

    static clearLayers() {
        for (var i = this.viewer.imageryLayers.length - 1; i >= 0; --i) {
            if (!this.viewer.imageryLayers.get(i).isBaseLayer()) {
                this.viewer.imageryLayers.remove(this.viewer.imageryLayers.get(i));
            }
        }
    }

    //删除wms
    static closelayer() {
        //wms服务
        this.viewer.imageryLayers.remove(this.privide);
    }

    static addPoint(pLon, pLat, pAlt, isSelected = false,pointId = null) {
        var pointEntity = this.viewer.entities.add({
            id: pointId,
            position: Cesium.Cartesian3.fromDegrees(pLon, pLat, pAlt),
            point: {
                pixelSize: 10,
                color: isSelected ? Cesium.Color.RED : Cesium.Color.YELLOW,
            },
        });
        return pointEntity;
    }
    //移除某个点
    static removePoint() {
        this.viewer.entities.removeById("theNewPoint");
        this.viewer.entities.removeAll();
    }
    //修改点的位置
    static clickToAddPoint(callback){
        //清空之前的handler
        if (this.addPointHandler) {
            this.addPointHandler.destroy();
        }
                var scene = this.viewer.scene;
                this.addPointHandler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
                const that = this;
                this.addPointHandler.setInputAction(function (movement) {
                    // 清除历史单击点
                    var cartesian = that.viewer.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 lng = Number(longitudeString);
                        let lat = Number(latitudeString);
                        const positions = [lng, lat];
                        that.viewer.entities.removeById("theNewPoint");
                        that.viewer.entities.add({
                            id: "theNewPoint",
                            position: cartesian,
                            point: {
                                color: Cesium.Color.fromCssColorString('#9cf7e3'),
                                pixelSize: 10
                                // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
                            }
                        });
                        //通过callback函数将数据传递到外部使用
                       callback(positions);
                    }
              }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
    //销毁监听
    static destroyClickToAddPoint(){
        if(this.addPointHandler){
            this.addPointHandler.destroy();
        }
    }
    //鼠标点击
    static handleClick() {
        var scene = this.viewer.scene;
        this.clickShowPopHandler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
        const that = this;
        that.clickShowPopHandler.setInputAction(function (movement) {
            console.log(123);
            // 清除历史单击点
            that.clickShowPopHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
            // movement.position 像素的x、y坐标
            var cartesian = that.viewer.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;
            // 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;
                // 清空容器
                const pendPreview =
                    document.getElementById("PendPreview") ||
                    document.getElementById("cesium_container") ||
                    document.getElementById("cesiumView") ||
                    document.getElementById("auditPreview") ||
                    document.getElementById("checkedPreview") ||
                    document.getElementById("sceneShowContent");
                const closeIcon = document.getElementsByClassName("close-icon");
                if (closeIcon.length > 0) {
                    for (let i = 0; i < closeIcon.length; i++) {
                        pendPreview.removeChild(closeIcon[i]);
                    }
                }
                const closeDom = document.createElement("div");
                closeDom.classList.add("close-icon");
                closeDom.style.cssText = `display: none;`;
                closeDom.innerHTML = `
                    <div style='padding: 20px; border-radius: 10px; background: white; font-family: sans-serif; font-size: 20px;'>
                        <div style=''>像素值:${pValue}</div>
                        <img class='closeIcon' src='${iconClose}' style='cursor: pointer; width: 20px; height: 20px; position: absolute; top: 3px; right: 3px;' />
                    </div>
                `;
                that.viewer.container.append(closeDom);
                scene.postRender.addEventListener(() => {
                    const windowCoord = Cesium.SceneTransforms.wgs84ToWindowCoordinates(
                        that.viewer.scene,
                        Cesium.Cartesian3.fromDegrees(
                            Number(longitudeString),
                            Number(latitudeString),
                            50
                        )
                    );
                    // const x = windowCoord.x - closeDom.offsetWidth / 2
                    // const y = windowCoord.y - closeDom.offsetHeight
                    const x = windowCoord.x;
                    const y = windowCoord.y;
                    closeDom.style.cssText = `
                        position: absolute;
                        top: 0;
                        left: 0;
                        transform: translate3d(${Math.round(x)}px, ${Math.round(y)}px, 0);
                        display: inline-block;
                    `;
                });
                const close = document.getElementsByClassName("closeIcon")[0];
                close.addEventListener(
                    "click",
                    () => {
                        const pendPreview =
                            document.getElementById("PendPreview") ||
                            document.getElementById("cesium_container") ||
                            document.getElementById("cesiumView") ||
                            document.getElementById("auditPreview") ||
                            document.getElementById("checkedPreview") ||
                            document.getElementById("sceneShowContent");
                        const closeIcon = document.getElementsByClassName("close-icon");
                        if (closeIcon.length > 0) {
                            for (let i = 0; i < closeIcon.length; i++) {
                                pendPreview.removeChild(closeIcon[i]);
                            }
                        }
                    },
                    false
                );

                // pValue = res;
                // 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.viewer.dataSources.add(dataSource);
            });
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
    //销毁点击事件
    static destoryHandleClick(){
        if(this.clickShowPopHandler){
            this.clickShowPopHandler.destroy()
        }
    }
}

export default CesiumUtils;
