let config = null, viewer = null, vectors = [], piontClouds = [], model = null, ESRIImg = null, TDTVec = null;

/**
 * 读取配置文件
 */
$.getJSON("Build/Static/config.json", "", function (data) {
    config = data;
    $(document).ready(function () {
        initialize();
    });
});

/**
 * 初始化场景
 */
function initialize() {
    viewer = Freedo.FdApp.createDefaultViewer('mainscene', {
        homeButton: false,
        scene3DOnly : true,
        contextOptions: {
            webgl: {
                alpha: true,
                depth: false,
                stencil: true,
                antialias: true,
                premultipliedAlpha: true,
                preserveDrawingBuffer: true,
                failIfMajorPerformanceCaveat: true
            }
        }
    }, {});
    viewer.scene.requestRenderMode = false;
    viewer.extend(Freedo.FdTools.FdNavigationMixin);
    $("div[title$='重置视图']").hide();
    let terrainManager = new Freedo.FdTools.FdTerrain(viewer);
    terrainManager.setTerrain(config.data.terrain.url, 'STK');
    TDTVec = viewer.imageryLayers.addImageryProvider(new Freedo.WebMapTileServiceImageryProvider({
        name: config.data.layer.TDTVec.name,
        url: config.data.layer.TDTVec.url,
        layer: config.data.layer.TDTVec.layer,
        style: config.data.layer.TDTVec.style,
        format: config.data.layer.TDTVec.format,
        tileMatrixSetID: config.data.layer.TDTVec.tileMatrixSetID,
        minimumLevel: config.data.layer.TDTVec.minimumLevel,
        maximumLevel: config.data.layer.TDTVec.maximumLevel,
        show: config.data.layer.TDTVec.show,
    }));
    ESRIImg = viewer.imageryLayers.addImageryProvider(new Freedo.ArcGisMapServerImageryProvider({
        name: config.data.layer.ESRIImg.name,
        url: config.data.layer.ESRIImg.url,
        layer: config.data.layer.ESRIImg.layer,
        style: config.data.layer.ESRIImg.style,
        format: config.data.layer.ESRIImg.format,
        tileMatrixSetID: config.data.layer.ESRIImg.tileMatrixSetID,
        minimumLevel: config.data.layer.ESRIImg.minimumLevel,
        maximumLevel: config.data.layer.ESRIImg.maximumLevel,
        enablePickFeatures: config.data.layer.ESRIImg.enablePickFeatures,
        show: config.data.layer.ESRIImg.show,
    }));
    $('#tree_layer').tree('check', $('#tree_layer').tree('find', 11).target);
    for (let i = 0; i < config.data.pointclouds.url.length; i++) {
        piontClouds.push(add3Dtile(config.data.pointclouds.url[i], true));
    }
    for (let i = 0; i < config.data.vector.url.length; i++) {
        addVectors(config.data.vector.url[i]);
    }
    model = add3Dtile(config.data.model.url);
    model.show = false;
    viewer.camera.flyTo({
        destination: new Freedo.Cartesian3.fromDegrees(config.InitialPosition.lon, config.InitialPosition.lat, config.InitialPosition.height),
        orientation: new Freedo.HeadingPitchRoll.fromDegrees(config.InitialOrientation.heading, config.InitialOrientation.pitch, config.InitialOrientation.roll)
    });
}

/**
 * 添加三维模型
 * @param url 模型url
 * @param isStyle 是否需要自定义渲染
 * @returns {Cesium3DTile} 3dtile
 */
function add3Dtile(url, isStyle) {
    let tile = viewer.scene.primitives.add(new Freedo.FreedoPModelset({
        url: url,
        dynamicScreenSpaceError: true,
        maximumMemoryUsage: 512,
        maximumAbsoluteMemoryUsage: 2048,
        maximumScreenSpaceError: 2,        //最大的屏幕空间误差
        maximumNumberOfLoadedTiles: 1000,  //最大加载瓦片个数
    }));
    tile.readyPromise.then(function (tileset) {
        let x = 0,
            y = 0,
            z = 3;
        let boundingSphere = tileset.boundingSphere;
        let cartographic = Freedo.Cartographic.fromCartesian(boundingSphere.center);
        let surface = Freedo.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
        let offset = Freedo.Cartesian3.fromRadians((cartographic.longitude + x), (cartographic.latitude + y), z);
        let translation = Freedo.Cartesian3.subtract(offset, surface, new Freedo.Cartesian3());
        tile.modelMatrix = Freedo.Matrix4.fromTranslation(translation);
    });
    if (isStyle) {
        tile.style = new Freedo.Cesium3DTileStyle({
            color: {
                conditions: [
                    ["${Classification} >=16.9", "rgb(232, 20, 40)"],
                    ["${Classification} >=15.9", "rgb(243, 0, 0)"],
                    ["${Classification} >=14.9", "rgb(68, 72, 93)"],
                    ["${Classification} >=13.9", "rgb(1, 41, 247)"],
                    ["${Classification} >=12.9", "rgb(228, 228, 216)"],
                    ["${Classification} >=10.9", "rgb(123, 125, 7)"],
                    ["${Classification} >=9.9", "rgb(45, 45, 40)"],
                    ["${Classification} >=8.9", "rgba(127, 158, 249, 0.71)"],
                    ["${Classification} >=5.9", "rgb(183, 180, 170)"],
                    ["${Classification} >=4.9", "rgb(7, 128, 12)"],
                    ["${Classification} >= 3.9", "rgb(9, 81, 16)"],
                    ["${Classification} >= 2.9", "rgb(51, 78, 8)"],
                    ["${Classification} >= 1.9", "rgb(67, 76, 81)"],
                    ["true", "rgb(255 255, 255)"]
                ]
            }
        });
    }
    return tile;
}

/**
 * 添加矢量要素
 * @param path 要素路径
 * @returns {GeoJsonDataSource} 矢量数据集
 */
function addVectors(path) {
    let vector = Freedo.GeoJsonDataSource.load(path, {clampToGround: true});
    vector.then(function (dataSource) {
        dataSource.show = false;
        viewer.dataSources.add(dataSource);
        vectors.push(dataSource);
    });
    return vector;
}

/**
 * 图层控制
 * @param id 节点ID
 */
function changeLayer(id) {
    switch (id) {
        case 11:
            TDTVec.show = false;
            ESRIImg.show = true;
            viewer.imageryLayers.raiseToTop(ESRIImg);
            break;
        case 12:
            TDTVec.show = true;
            ESRIImg.show = false;
            viewer.imageryLayers.raiseToTop(TDTVec);
            break;
    }
}

/**
 * 显示图层
 * @param index 图层索引
 * @param isshow 是否显示
 */
function showTile(index, isshow) {
    piontClouds[index].show = isshow;
}

/**
 * 显示模型
 * @param isshow 是否显示
 */
function showModel(isshow) {
    model.show = isshow;
}

/**
 * 添加矢量数据
 * @param index 图层索引
 * @param isshow 是否显示
 */
function showVector(index, isshow) {
    vectors[index].show = isshow;
}

/**
 * 获取屏幕中心点
 * @param scene 场景
 * @returns {Cartesian3} 屏幕中心点坐标
 */
function getCenter(scene) {
    var ray = new Freedo.Ray(scene.camera.positionWC, scene.camera.directionWC);
    return scene.globe.pick(ray, scene);
}

/**
 * 获取当前高度值
 * @returns {number}
 */
function getH() {
    return Math.ceil(viewer.camera.positionCartographic.height);
}

/**
 * 缩放至初始化位置
 */
function flyToHome() {
    viewer.camera.flyTo({
        destination: new Freedo.Cartesian3.fromDegrees(config.InitialPosition.lon, config.InitialPosition.lat, config.InitialPosition.height),
        orientation: new Freedo.HeadingPitchRoll.fromDegrees(config.InitialOrientation.heading, config.InitialOrientation.pitch, config.InitialOrientation.roll)
    });
}

/**
 * 快速指北
 */
function setNorth() {
    var scene = viewer.scene;
    var camera = scene.camera;
    scene.screenSpaceCameraController.enableInputs = false
    var heading = camera.heading;
    var pitch = camera.pitch;
    var range = getH();
    camera.constrainedAxis = Freedo.Cartesian3.UNIT_Z;
    var transform = Freedo.Transforms.eastNorthUpToFixedFrame(getCenter(scene));
    camera.lookAtTransform(transform, new Freedo.HeadingPitchRange(heading, pitch, range));
    var Exection = function TimeExecution() {
        var pitch = Freedo.Math.toDegrees(camera.pitch);
        var heading = Freedo.Math.toDegrees(camera.heading);
        if (heading > 1 && heading < 179) {
            camera.rotateRight(0.01);
        } else if (heading > 181 && heading < 359) {
            camera.rotateLeft(0.01);
        } else if ((heading >= 0 && heading <= 1) || (heading >= 359 && heading <= 360)) {
            camera.lookAtTransform(Freedo.Matrix4.IDENTITY);
            viewer.clock.onTick.removeEventListener(Exection);
            scene.screenSpaceCameraController.enableInputs = true;
            scene.screenSpaceCameraController.enableTilt = true;

        }
    };
    viewer.clock.onTick.addEventListener(Exection);
}

/**
 * 全屏
 * @param element 全屏div
 */
function launchIntoFullscreen(element) {
    if (element.requestFullscreen) {
        element.requestFullscreen();
    }
    else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
    }
    else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
    }
    else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
    }
}

/**
 * 退出全屏
 */
function exitFullscreen() {
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
    }
}

/**
 * 场景保存
 */
function saveScene() {
    let dataUrl = viewer.scene.canvas.toDataURL('image/jpeg', 0.9);
    let a = document.createElement("a");
    document.body.appendChild(a);
    a.href = dataUrl;
    console.log(dataUrl);
    a.download = "场景截图";
    a.click();
}

/**
 * 全景浏览
 * @param isPanorama 是否打开全景开关
 */
function setPanorama(isPanorama) {
    if (isPanorama) {
        viewer.panorama = new Panorama(viewer, config.data.panorama);

    } else {
        viewer.panorama.destroy();
        viewer.panorama = null;

    }
}