import './plugins/fixGltf'
import './plugins/HeatmapImageryProvider'
import './plugins/SpirographPositionProperty'
import { createMVTWithStyle } from './mvt'

import {
    drawRectangle
} from './rectangle.js'
import {  points2 } from './heatmap'

function main() {
    
    var $loadingIndicator = document.getElementById('loadingIndicator')

    var viewer;
    try {

        var Google = new Cesium.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 Cesium.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 Cesium.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
        })


        var PBF = createMVTWithStyle(Cesium, ol, createMapboxStreetsV6Style, {
            url: 'pbf/{z}/{x}/{y}.pbf',
            key: "pk.eyJ1IjoibXV5YW8xOTg3IiwiYSI6ImNpcm9ueHd6cjAwNzZoa20xazY1aWlubjIifQ.5tLtC5j1rh8Eqjlyrq3OaA"
        });

        


        viewer = window.viewer = new Cesium.Viewer('cesiumContainer', {
            resolutionScale: 1,
            terrainProviderViewModels: [],
            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,
            imageryProvider: tdtImagerLayerProvider,
        });

        viewer.extend(Cesium.viewerCesiumNavigationMixin, {});

        //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: Cesium.Cartesian3.fromDegrees(113.07242100, 22.58652789, 1000.0),
            orientation: {
                heading: 5.205384767667713,
                pitch: -1.0220630084744524,
                roll: 6.27919703978724
            }
        })


        var heatmap = new Cesium.HeatmapImageryProvider({
            data: points2,
            heatmapoptions: {
                radius: 30,
                max: 300,
                xField: "lng",
                yField: "lat",
                valueField: "count",
            }
        });

        viewer.imageryLayers.addImageryProvider(heatmap)

        var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);

        drawRectangle(Cesium, viewer, handler, function(coords) {
            console.log(coords)
            var heatMap1 = createHeatMap(getData(1000).max, getData(1000).data);
            createRectangle(viewer, [coords.west, coords.south, coords.east, coords.north], heatMap1);
        });

        var tileset = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
            url: "/static/tiles/temp/tileset.json", //Cesium.IonResource.fromAssetId(item) //'static/tiles/tileset.json'
            //maximumMemoryUsage:200
            maximumScreenSpaceError: 25,
            maximumNumberOfLoadedTiles: 1000
        }));

        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) {
            console.log(error);
        });

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


    } catch (exception) {
        $loadingIndicator.style.display = 'none';
        var message = Cesium.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()
}