import './plugins/fixGltf'
import './plugins/SpirographPositionProperty'
import {
    UrlTemplateImageryProvider,
    WebMapTileServiceImageryProvider,
    GeographicTilingScheme,
    Viewer,
    ScreenSpaceEventHandler,
    Cesium3DTileset,
    SceneMode,
    formatError,
    Cartesian3,
    Resource
} from "cesium/Cesium";
import CesiumNavigation from "./plugins/cesium-navigation-es6";
import HeatmapImageryProvider from './plugins/HeatmapImageryProvider'
import { renderStyle } from './plugins/mvt'
import { points2 } from './heatmap'
import bus from '../utils/bus'

async function main() {

    var $loadingIndicator = document.getElementById('loadingIndicator')

    var viewer;
    try {

        var Google = new UrlTemplateImageryProvider({
            url: "http://mt3.google.cn/vt/lyrs=y@110&hl=zh-CN&gl=cn&src=app&x={x}&y={y}&z={z}&s=Ga",
        })

        //天地图影像服务
        var tdtImagerLayerProvider = new WebMapTileServiceImageryProvider({
            url: "http://{s}.tianditu.gov.cn/img_c/wmts?tk=463a3e5ee4e35c17ae02564f18f95655&service=wmts&request=GetTile&version=1.0.0" +
                "&LAYER=img&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}" +
                "&style=default&format=tiles",
            layer: "tdtImg_c",
            style: "default",
            format: "tiles",
            tileMatrixSetID: "c",
            subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
            tilingScheme: new GeographicTilingScheme(),
            tileMatrixLabels: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19"],
            maximumLevel: 18,
            show: false
        })


        viewer = window.viewer = new Viewer('cesiumContainer', {
            resolutionScale: 1,
            terrainProviderViewModels: false,
            animation: false, //动画控制不显示     
            baseLayerPicker: false,
            fullscreenButton: false, //全屏按钮,默认显示true
            geocoder: false, //地名查找,默认true
            timeline: false, //时间线,默认true
            vrButton: false, //双屏模式,默认不显示false
            homeButton: true, //主页按钮，默认true 
            infoBox: false, //点击要素之后显示的信息,默认true
            selectionIndicator: false, //选中元素显示,默认true
            sceneModePicker: false, //是否显示投影方式控件
            navigationHelpButton: true, //是否显示帮助信息控件
            maximumRenderTimeChange: Infinity,
            requestRenderMode: true,
            scene3DOnly: true,
            imageryProvider: Google,
        });

        CesiumNavigation(viewer, {
            // defaultResetView : Rectangle.fromDegrees(80, 22, 130, 50),
            enableCompass: true,
            enableZoomControls: true,
            enableDistanceLegend: true,
            enableCompassOuterRing: true
        });

        //使用太阳作为光源，可以照亮地球。
        viewer.scene.globe.enableLighting = false;
        //关闭地面大气效果，（默认为开启状态）
        viewer.scene.globe.showGroundAtmosphere = false;
        //FPS 帧率显示
        //viewer.scene.debugShowFramesPerSecond = true;

        //viewer.scene.debugShowFramesPerSecond = true;
        //viewer.scene.screenSpaceCameraController.enableTranslate = false;
        //viewer.scene.screenSpaceCameraController.enableTilt = false;
        //viewer.scene.screenSpaceCameraController.enableLook = false;
        //viewer.scene.screenSpaceCameraController.enableCollisionDetection = false;

        // var imageryLayers = viewer.imageryLayers;
        // imageryLayers.addImageryProvider(PBF);


        viewer.camera.setView({
            destination: Cartesian3.fromDegrees(113.07242100, 22.58652789, 1000.0),
            orientation: {
                heading: 5.205384767667713,
                pitch: -1.0220630084744524,
                roll: 6.27919703978724
            }
        })

        var resource = Resource.createIfNeeded('config.json?_'+Date.now());
        var config = await resource.fetchJson()

        bus.$emit('config', config)

        if (config.tileset) {
            var tileset = viewer.scene.primitives.add(new Cesium3DTileset({
                url: config.tileset,
                maximumScreenSpaceError: 20,
                maximumNumberOfLoadedTiles: 500
            }));

            tileset.readyPromise.then(function(tileset) {
                //viewer.entities.values.forEach(item=>item.show = true)
                viewer.zoomTo(tileset);
                viewer.homeButton.viewModel.command.beforeExecute.addEventListener(function(e) {
                    e.cancel = true;
                    //viewer.zoomTo(tileset,new Cesium.HeadingPitchRoll(5.208372654027434, -0.22688012666187052, 6.281056493524698));
                    //viewer.zoomTo(tileset,new Cesium.HeadingPitchRange(5.208372654027434, -0.22688012666187052, tileset.boundingSphere.radius * 2.0));
                    viewer.zoomTo(tileset);
                });
            }).otherwise(function(error) {

            });
        }


        viewer.camera.changed.addEventListener(
            function() {
                if (viewer.camera._suspendTerrainAdjustment && viewer.scene.mode === SceneMode.SCENE3D) {
                    viewer.camera._suspendTerrainAdjustment = false;
                    viewer.camera._adjustHeightForTerrain();
                }
            }
        );


        bus.$on("setLayer", layer => {
            var layers = viewer.imageryLayers._layers
            var find
            if (layer.checked) {
                for (let i = 0; i < layers.length; i++) {
                    if (layers[i].imageryProvider.name == layer.name) {
                        find = layers[i]
                        break
                    }
                }
                if (find) {
                    find.show = true
                } else {
                    var addLayer;
                    if(layer.type === 'geodata' && layer.url){
                        addLayer = renderStyle(ol, createMapboxStreetsV6Style, {
                            url: layer.url+'/{z}/{x}/{y}.pbf',
                            key: "pk.eyJ1IjoibXV5YW8xOTg3IiwiYSI6ImNpcm9ueHd6cjAwNzZoa20xazY1aWlubjIifQ.5tLtC5j1rh8Eqjlyrq3OaA"
                        });
                    }else if(layer.type === 'heatmap'){
                        addLayer = new HeatmapImageryProvider({
                            data: points2,
                            heatmapoptions: {
                                radius: 30,
                                //max: 10,
                                xField: "lng",
                                yField: "lat",
                                valueField: "count",
                            }
                        });
                    }

                    if(addLayer){
                        addLayer.name = layer.name
                        viewer.imageryLayers.addImageryProvider(addLayer)
                    }
                }
            } else {
                for (let i = 0; i < layers.length; i++) {
                    if (layers[i].imageryProvider.name == layer.name) {
                        find = layers[i]
                        break
                    }
                }
                if (find) {
                    find.show = false
                }
            }
        });


    } catch (exception) {
        $loadingIndicator.style.display = 'none';
        var message = formatError(exception);
        console.error(message);
        if (!document.querySelector('.cesium-widget-errorPanel')) {
            window.alert(message); //eslint-disable-line no-alert
        }
        return;
    }

    $loadingIndicator.style.display = 'none';
}

export function start() {
    main()
}